babylon.no-module.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  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 if (otherMesh.subMeshes) {
  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. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  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. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. this.x = x;
  2190. this.y = y;
  2191. }
  2192. /**
  2193. * Gets a string with the Vector2 coordinates
  2194. * @returns a string with the Vector2 coordinates
  2195. */
  2196. Vector2.prototype.toString = function () {
  2197. return "{X: " + this.x + " Y:" + this.y + "}";
  2198. };
  2199. /**
  2200. * Gets class name
  2201. * @returns the string "Vector2"
  2202. */
  2203. Vector2.prototype.getClassName = function () {
  2204. return "Vector2";
  2205. };
  2206. /**
  2207. * Gets current vector hash code
  2208. * @returns the Vector2 hash code as a number
  2209. */
  2210. Vector2.prototype.getHashCode = function () {
  2211. var hash = this.x || 0;
  2212. hash = (hash * 397) ^ (this.y || 0);
  2213. return hash;
  2214. };
  2215. // Operators
  2216. /**
  2217. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2218. * @param array defines the source array
  2219. * @param index defines the offset in source array
  2220. * @returns the current Vector2
  2221. */
  2222. Vector2.prototype.toArray = function (array, index) {
  2223. if (index === void 0) { index = 0; }
  2224. array[index] = this.x;
  2225. array[index + 1] = this.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Copy the current vector to an array
  2230. * @returns a new array with 2 elements: the Vector2 coordinates.
  2231. */
  2232. Vector2.prototype.asArray = function () {
  2233. var result = new Array();
  2234. this.toArray(result, 0);
  2235. return result;
  2236. };
  2237. /**
  2238. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2239. * @param source defines the source Vector2
  2240. * @returns the current updated Vector2
  2241. */
  2242. Vector2.prototype.copyFrom = function (source) {
  2243. this.x = source.x;
  2244. this.y = source.y;
  2245. return this;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the given floats
  2249. * @param x defines the first coordinate
  2250. * @param y defines the second coordinate
  2251. * @returns the current updated Vector2
  2252. */
  2253. Vector2.prototype.copyFromFloats = function (x, y) {
  2254. this.x = x;
  2255. this.y = y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the Vector2 coordinates with the given floats
  2260. * @param x defines the first coordinate
  2261. * @param y defines the second coordinate
  2262. * @returns the current updated Vector2
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Add another vector with the current one
  2269. * @param otherVector defines the other vector
  2270. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2271. */
  2272. Vector2.prototype.add = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2277. * @param otherVector defines the other vector
  2278. * @param result defines the target vector
  2279. * @returns the unmodified current Vector2
  2280. */
  2281. Vector2.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2288. * @param otherVector defines the other vector
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2
  2300. */
  2301. Vector2.prototype.addVector3 = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2306. * @param otherVector defines the other vector
  2307. * @returns a new Vector2
  2308. */
  2309. Vector2.prototype.subtract = function (otherVector) {
  2310. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2311. };
  2312. /**
  2313. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2314. * @param otherVector defines the other vector
  2315. * @param result defines the target vector
  2316. * @returns the unmodified current Vector2
  2317. */
  2318. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2319. result.x = this.x - otherVector.x;
  2320. result.y = this.y - otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns the current updated Vector2
  2327. */
  2328. Vector2.prototype.subtractInPlace = function (otherVector) {
  2329. this.x -= otherVector.x;
  2330. this.y -= otherVector.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Multiplies in place the current Vector2 coordinates by the given ones
  2335. * @param otherVector defines the other vector
  2336. * @returns the current updated Vector2
  2337. */
  2338. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2339. this.x *= otherVector.x;
  2340. this.y *= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2358. result.x = this.x * otherVector.x;
  2359. result.y = this.y * otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2364. * @param x defines the first coordinate
  2365. * @param y defines the second coordinate
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.divideToRef = function (otherVector, result) {
  2386. result.x = this.x / otherVector.x;
  2387. result.y = this.y / otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Divides the current Vector3 coordinates by the given ones
  2392. * @param otherVector defines the other vector
  2393. * @returns the current updated Vector2
  2394. */
  2395. Vector2.prototype.divideInPlace = function (otherVector) {
  2396. return this.divideToRef(otherVector, this);
  2397. };
  2398. /**
  2399. * Gets a new Vector2 with current Vector2 negated coordinates
  2400. * @returns a new Vector2
  2401. */
  2402. Vector2.prototype.negate = function () {
  2403. return new Vector2(-this.x, -this.y);
  2404. };
  2405. /**
  2406. * Multiply the Vector2 coordinates by scale
  2407. * @param scale defines the scaling factor
  2408. * @returns the current updated Vector2
  2409. */
  2410. Vector2.prototype.scaleInPlace = function (scale) {
  2411. this.x *= scale;
  2412. this.y *= scale;
  2413. return this;
  2414. };
  2415. /**
  2416. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2417. * @param scale defines the scaling factor
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.scale = function (scale) {
  2421. var result = new Vector2(0, 0);
  2422. this.scaleToRef(scale, result);
  2423. return result;
  2424. };
  2425. /**
  2426. * Scale the current Vector2 values by a factor to a given Vector2
  2427. * @param scale defines the scale factor
  2428. * @param result defines the Vector2 object where to store the result
  2429. * @returns the unmodified current Vector2
  2430. */
  2431. Vector2.prototype.scaleToRef = function (scale, result) {
  2432. result.x = this.x * scale;
  2433. result.y = this.y * scale;
  2434. return this;
  2435. };
  2436. /**
  2437. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2438. * @param scale defines the scale factor
  2439. * @param result defines the Vector2 object where to store the result
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2443. result.x += this.x * scale;
  2444. result.y += this.y * scale;
  2445. return this;
  2446. };
  2447. /**
  2448. * Gets a boolean if two vectors are equals
  2449. * @param otherVector defines the other vector
  2450. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2451. */
  2452. Vector2.prototype.equals = function (otherVector) {
  2453. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2454. };
  2455. /**
  2456. * Gets a boolean if two vectors are equals (using an epsilon value)
  2457. * @param otherVector defines the other vector
  2458. * @param epsilon defines the minimal distance to consider equality
  2459. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2460. */
  2461. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2462. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2463. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2464. };
  2465. // Properties
  2466. /**
  2467. * Gets the length of the vector
  2468. * @returns the vector length (float)
  2469. */
  2470. Vector2.prototype.length = function () {
  2471. return Math.sqrt(this.x * this.x + this.y * this.y);
  2472. };
  2473. /**
  2474. * Gets the vector squared length
  2475. * @returns the vector squared length (float)
  2476. */
  2477. Vector2.prototype.lengthSquared = function () {
  2478. return (this.x * this.x + this.y * this.y);
  2479. };
  2480. // Methods
  2481. /**
  2482. * Normalize the vector
  2483. * @returns the current updated Vector2
  2484. */
  2485. Vector2.prototype.normalize = function () {
  2486. var len = this.length();
  2487. if (len === 0)
  2488. return this;
  2489. var num = 1.0 / len;
  2490. this.x *= num;
  2491. this.y *= num;
  2492. return this;
  2493. };
  2494. /**
  2495. * Gets a new Vector2 copied from the Vector2
  2496. * @returns a new Vector2
  2497. */
  2498. Vector2.prototype.clone = function () {
  2499. return new Vector2(this.x, this.y);
  2500. };
  2501. // Statics
  2502. /**
  2503. * Gets a new Vector2(0, 0)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.Zero = function () {
  2507. return new Vector2(0, 0);
  2508. };
  2509. /**
  2510. * Gets a new Vector2(1, 1)
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.One = function () {
  2514. return new Vector2(1, 1);
  2515. };
  2516. /**
  2517. * Gets a new Vector2 set from the given index element of the given array
  2518. * @param array defines the data source
  2519. * @param offset defines the offset in the data source
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.FromArray = function (array, offset) {
  2523. if (offset === void 0) { offset = 0; }
  2524. return new Vector2(array[offset], array[offset + 1]);
  2525. };
  2526. /**
  2527. * Sets "result" from the given index element of the given array
  2528. * @param array defines the data source
  2529. * @param offset defines the offset in the data source
  2530. * @param result defines the target vector
  2531. */
  2532. Vector2.FromArrayToRef = function (array, offset, result) {
  2533. result.x = array[offset];
  2534. result.y = array[offset + 1];
  2535. };
  2536. /**
  2537. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2538. * @param value1 defines 1st point of control
  2539. * @param value2 defines 2nd point of control
  2540. * @param value3 defines 3rd point of control
  2541. * @param value4 defines 4th point of control
  2542. * @param amount defines the interpolation factor
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2546. var squared = amount * amount;
  2547. var cubed = amount * squared;
  2548. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2549. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2550. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2551. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2552. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2553. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2554. return new Vector2(x, y);
  2555. };
  2556. /**
  2557. * 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".
  2558. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2559. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2560. * @param value defines the value to clamp
  2561. * @param min defines the lower limit
  2562. * @param max defines the upper limit
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.Clamp = function (value, min, max) {
  2566. var x = value.x;
  2567. x = (x > max.x) ? max.x : x;
  2568. x = (x < min.x) ? min.x : x;
  2569. var y = value.y;
  2570. y = (y > max.y) ? max.y : y;
  2571. y = (y < min.y) ? min.y : y;
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2576. * @param value1 defines the 1st control point
  2577. * @param tangent1 defines the outgoing tangent
  2578. * @param value2 defines the 2nd control point
  2579. * @param tangent2 defines the incoming tangent
  2580. * @param amount defines the interpolation factor
  2581. * @returns a new Vector2
  2582. */
  2583. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2584. var squared = amount * amount;
  2585. var cubed = amount * squared;
  2586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2588. var part3 = (cubed - (2.0 * squared)) + amount;
  2589. var part4 = cubed - squared;
  2590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2596. * @param start defines the start vector
  2597. * @param end defines the end vector
  2598. * @param amount defines the interpolation factor
  2599. * @returns a new Vector2
  2600. */
  2601. Vector2.Lerp = function (start, end, amount) {
  2602. var x = start.x + ((end.x - start.x) * amount);
  2603. var y = start.y + ((end.y - start.y) * amount);
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Gets the dot product of the vector "left" and the vector "right"
  2608. * @param left defines first vector
  2609. * @param right defines second vector
  2610. * @returns the dot product (float)
  2611. */
  2612. Vector2.Dot = function (left, right) {
  2613. return left.x * right.x + left.y * right.y;
  2614. };
  2615. /**
  2616. * Returns a new Vector2 equal to the normalized given vector
  2617. * @param vector defines the vector to normalize
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Normalize = function (vector) {
  2621. var newVector = vector.clone();
  2622. newVector.normalize();
  2623. return newVector;
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2627. * @param left defines 1st vector
  2628. * @param right defines 2nd vector
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Minimize = function (left, right) {
  2632. var x = (left.x < right.x) ? left.x : right.x;
  2633. var y = (left.y < right.y) ? left.y : right.y;
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2638. * @param left defines 1st vector
  2639. * @param right defines 2nd vector
  2640. * @returns a new Vector2
  2641. */
  2642. Vector2.Maximize = function (left, right) {
  2643. var x = (left.x > right.x) ? left.x : right.x;
  2644. var y = (left.y > right.y) ? left.y : right.y;
  2645. return new Vector2(x, y);
  2646. };
  2647. /**
  2648. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2649. * @param vector defines the vector to transform
  2650. * @param transformation defines the matrix to apply
  2651. * @returns a new Vector2
  2652. */
  2653. Vector2.Transform = function (vector, transformation) {
  2654. var r = Vector2.Zero();
  2655. Vector2.TransformToRef(vector, transformation, r);
  2656. return r;
  2657. };
  2658. /**
  2659. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2660. * @param vector defines the vector to transform
  2661. * @param transformation defines the matrix to apply
  2662. * @param result defines the target vector
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Determines if a given vector is included in a triangle
  2672. * @param p defines the vector to test
  2673. * @param p0 defines 1st triangle point
  2674. * @param p1 defines 2nd triangle point
  2675. * @param p2 defines 3rd triangle point
  2676. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Gets the distance between the vectors "value1" and "value2"
  2687. * @param value1 defines first vector
  2688. * @param value2 defines second vector
  2689. * @returns the distance between vectors
  2690. */
  2691. Vector2.Distance = function (value1, value2) {
  2692. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2693. };
  2694. /**
  2695. * Returns the squared distance between the vectors "value1" and "value2"
  2696. * @param value1 defines first vector
  2697. * @param value2 defines second vector
  2698. * @returns the squared distance between vectors
  2699. */
  2700. Vector2.DistanceSquared = function (value1, value2) {
  2701. var x = value1.x - value2.x;
  2702. var y = value1.y - value2.y;
  2703. return (x * x) + (y * y);
  2704. };
  2705. /**
  2706. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Center = function (value1, value2) {
  2712. var center = value1.add(value2);
  2713. center.scaleInPlace(0.5);
  2714. return center;
  2715. };
  2716. /**
  2717. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2718. * @param p defines the middle point
  2719. * @param segA defines one point of the segment
  2720. * @param segB defines the other point of the segment
  2721. * @returns the shortest distance
  2722. */
  2723. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2724. var l2 = Vector2.DistanceSquared(segA, segB);
  2725. if (l2 === 0.0) {
  2726. return Vector2.Distance(p, segA);
  2727. }
  2728. var v = segB.subtract(segA);
  2729. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2730. var proj = segA.add(v.multiplyByFloats(t, t));
  2731. return Vector2.Distance(p, proj);
  2732. };
  2733. return Vector2;
  2734. }());
  2735. BABYLON.Vector2 = Vector2;
  2736. /**
  2737. * Classed used to store (x,y,z) vector representation
  2738. * A Vector3 is the main object used in 3D geometry
  2739. * It can represent etiher the coordinates of a point the space, either a direction
  2740. * Reminder: Babylon.js uses a left handed forward facing system
  2741. */
  2742. var Vector3 = /** @class */ (function () {
  2743. /**
  2744. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2745. * @param x defines the first coordinates (on X axis)
  2746. * @param y defines the second coordinates (on Y axis)
  2747. * @param z defines the third coordinates (on Z axis)
  2748. */
  2749. function Vector3(
  2750. /**
  2751. * Defines the first coordinates (on X axis)
  2752. */
  2753. x,
  2754. /**
  2755. * Defines the second coordinates (on Y axis)
  2756. */
  2757. y,
  2758. /**
  2759. * Defines the third coordinates (on Z axis)
  2760. */
  2761. z) {
  2762. this.x = x;
  2763. this.y = y;
  2764. this.z = z;
  2765. }
  2766. /**
  2767. * Creates a string representation of the Vector3
  2768. * @returns a string with the Vector3 coordinates.
  2769. */
  2770. Vector3.prototype.toString = function () {
  2771. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2772. };
  2773. /**
  2774. * Gets the class name
  2775. * @returns the string "Vector3"
  2776. */
  2777. Vector3.prototype.getClassName = function () {
  2778. return "Vector3";
  2779. };
  2780. /**
  2781. * Creates the Vector3 hash code
  2782. * @returns a number which tends to be unique between Vector3 instances
  2783. */
  2784. Vector3.prototype.getHashCode = function () {
  2785. var hash = this.x || 0;
  2786. hash = (hash * 397) ^ (this.y || 0);
  2787. hash = (hash * 397) ^ (this.z || 0);
  2788. return hash;
  2789. };
  2790. // Operators
  2791. /**
  2792. * Creates an array containing three elements : the coordinates of the Vector3
  2793. * @returns a new array of numbers
  2794. */
  2795. Vector3.prototype.asArray = function () {
  2796. var result = [];
  2797. this.toArray(result, 0);
  2798. return result;
  2799. };
  2800. /**
  2801. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2802. * @param array defines the destination array
  2803. * @param index defines the offset in the destination array
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.toArray = function (array, index) {
  2807. if (index === void 0) { index = 0; }
  2808. array[index] = this.x;
  2809. array[index + 1] = this.y;
  2810. array[index + 2] = this.z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2815. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2816. */
  2817. Vector3.prototype.toQuaternion = function () {
  2818. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2819. };
  2820. /**
  2821. * Adds the given vector to the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.addInPlace = function (otherVector) {
  2826. this.x += otherVector.x;
  2827. this.y += otherVector.y;
  2828. this.z += otherVector.z;
  2829. return this;
  2830. };
  2831. /**
  2832. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2833. * @param otherVector defines the second operand
  2834. * @returns the resulting Vector3
  2835. */
  2836. Vector3.prototype.add = function (otherVector) {
  2837. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2838. };
  2839. /**
  2840. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2841. * @param otherVector defines the second operand
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.addToRef = function (otherVector, result) {
  2846. result.x = this.x + otherVector.x;
  2847. result.y = this.y + otherVector.y;
  2848. result.z = this.z + otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Subtract the given vector from the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.subtractInPlace = function (otherVector) {
  2857. this.x -= otherVector.x;
  2858. this.y -= otherVector.y;
  2859. this.z -= otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.subtract = function (otherVector) {
  2868. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2869. };
  2870. /**
  2871. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2877. result.x = this.x - otherVector.x;
  2878. result.y = this.y - otherVector.y;
  2879. result.z = this.z - otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2884. * @param x defines the x coordinate of the operand
  2885. * @param y defines the y coordinate of the operand
  2886. * @param z defines the z coordinate of the operand
  2887. * @returns the resulting Vector3
  2888. */
  2889. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2890. return new Vector3(this.x - x, this.y - y, this.z - z);
  2891. };
  2892. /**
  2893. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2894. * @param x defines the x coordinate of the operand
  2895. * @param y defines the y coordinate of the operand
  2896. * @param z defines the z coordinate of the operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2901. result.x = this.x - x;
  2902. result.y = this.y - y;
  2903. result.z = this.z - z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2908. * @returns a new Vector3
  2909. */
  2910. Vector3.prototype.negate = function () {
  2911. return new Vector3(-this.x, -this.y, -this.z);
  2912. };
  2913. /**
  2914. * Multiplies the Vector3 coordinates by the float "scale"
  2915. * @param scale defines the multiplier factor
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.scaleInPlace = function (scale) {
  2919. this.x *= scale;
  2920. this.y *= scale;
  2921. this.z *= scale;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2926. * @param scale defines the multiplier factor
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.scale = function (scale) {
  2930. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2931. };
  2932. /**
  2933. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2934. * @param scale defines the multiplier factor
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.scaleToRef = function (scale, result) {
  2939. result.x = this.x * scale;
  2940. result.y = this.y * scale;
  2941. result.z = this.z * scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2946. * @param scale defines the scale factor
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the unmodified current Vector3
  2949. */
  2950. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2951. result.x += this.x * scale;
  2952. result.y += this.y * scale;
  2953. result.z += this.z * scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2958. * @param otherVector defines the second operand
  2959. * @returns true if both vectors are equals
  2960. */
  2961. Vector3.prototype.equals = function (otherVector) {
  2962. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2963. };
  2964. /**
  2965. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2966. * @param otherVector defines the second operand
  2967. * @param epsilon defines the minimal distance to define values as equals
  2968. * @returns true if both vectors are distant less than epsilon
  2969. */
  2970. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2971. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2972. 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);
  2973. };
  2974. /**
  2975. * Returns true if the current Vector3 coordinates equals the given floats
  2976. * @param x defines the x coordinate of the operand
  2977. * @param y defines the y coordinate of the operand
  2978. * @param z defines the z coordinate of the operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2982. return this.x === x && this.y === y && this.z === z;
  2983. };
  2984. /**
  2985. * Multiplies the current Vector3 coordinates by the given ones
  2986. * @param otherVector defines the second operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2990. this.x *= otherVector.x;
  2991. this.y *= otherVector.y;
  2992. this.z *= otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2997. * @param otherVector defines the second operand
  2998. * @returns the new Vector3
  2999. */
  3000. Vector3.prototype.multiply = function (otherVector) {
  3001. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3005. * @param otherVector defines the second operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3010. result.x = this.x * otherVector.x;
  3011. result.y = this.y * otherVector.y;
  3012. result.z = this.z * otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3017. * @param x defines the x coordinate of the operand
  3018. * @param y defines the y coordinate of the operand
  3019. * @param z defines the z coordinate of the operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3023. return new Vector3(this.x * x, this.y * y, this.z * z);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3027. * @param otherVector defines the second operand
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.prototype.divide = function (otherVector) {
  3031. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3032. };
  3033. /**
  3034. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3035. * @param otherVector defines the second operand
  3036. * @param result defines the Vector3 object where to store the result
  3037. * @returns the current Vector3
  3038. */
  3039. Vector3.prototype.divideToRef = function (otherVector, result) {
  3040. result.x = this.x / otherVector.x;
  3041. result.y = this.y / otherVector.y;
  3042. result.z = this.z / otherVector.z;
  3043. return this;
  3044. };
  3045. /**
  3046. * Divides the current Vector3 coordinates by the given ones.
  3047. * @param otherVector defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.divideInPlace = function (otherVector) {
  3051. return this.divideToRef(otherVector, this);
  3052. };
  3053. /**
  3054. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3055. * @param other defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.minimizeInPlace = function (other) {
  3059. if (other.x < this.x)
  3060. this.x = other.x;
  3061. if (other.y < this.y)
  3062. this.y = other.y;
  3063. if (other.z < this.z)
  3064. this.z = other.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3069. * @param other defines the second operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.maximizeInPlace = function (other) {
  3073. if (other.x > this.x)
  3074. this.x = other.x;
  3075. if (other.y > this.y)
  3076. this.y = other.y;
  3077. if (other.z > this.z)
  3078. this.z = other.z;
  3079. return this;
  3080. };
  3081. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3082. /**
  3083. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3084. */
  3085. get: function () {
  3086. var absX = Math.abs(this.x);
  3087. var absY = Math.abs(this.y);
  3088. if (absX !== absY) {
  3089. return true;
  3090. }
  3091. var absZ = Math.abs(this.z);
  3092. if (absX !== absZ) {
  3093. return true;
  3094. }
  3095. if (absY !== absZ) {
  3096. return true;
  3097. }
  3098. return false;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. // Properties
  3104. /**
  3105. * Gets the length of the Vector3
  3106. * @returns the length of the Vecto3
  3107. */
  3108. Vector3.prototype.length = function () {
  3109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Gets the squared length of the Vector3
  3113. * @returns squared length of the Vector3
  3114. */
  3115. Vector3.prototype.lengthSquared = function () {
  3116. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3117. };
  3118. /**
  3119. * Normalize the current Vector3.
  3120. * Please note that this is an in place operation.
  3121. * @returns the current updated Vector3
  3122. */
  3123. Vector3.prototype.normalize = function () {
  3124. var len = this.length();
  3125. if (len === 0 || len === 1.0)
  3126. return this;
  3127. var num = 1.0 / len;
  3128. this.x *= num;
  3129. this.y *= num;
  3130. this.z *= num;
  3131. return this;
  3132. };
  3133. /**
  3134. * Normalize the current Vector3 to a new vector
  3135. * @returns the new Vector3
  3136. */
  3137. Vector3.prototype.normalizeToNew = function () {
  3138. var normalized = new Vector3(0, 0, 0);
  3139. this.normalizeToRef(normalized);
  3140. return normalized;
  3141. };
  3142. /**
  3143. * Normalize the current Vector3 to the reference
  3144. * @param reference define the Vector3 to update
  3145. * @returns the updated Vector3
  3146. */
  3147. Vector3.prototype.normalizeToRef = function (reference) {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0) {
  3150. reference.set(this.x, this.y, this.z);
  3151. return reference;
  3152. }
  3153. var scale = 1.0 / len;
  3154. this.scaleToRef(scale, reference);
  3155. return reference;
  3156. };
  3157. /**
  3158. * Creates a new Vector3 copied from the current Vector3
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.clone = function () {
  3162. return new Vector3(this.x, this.y, this.z);
  3163. };
  3164. /**
  3165. * Copies the given vector coordinates to the current Vector3 ones
  3166. * @param source defines the source Vector3
  3167. * @returns the current updated Vector3
  3168. */
  3169. Vector3.prototype.copyFrom = function (source) {
  3170. this.x = source.x;
  3171. this.y = source.y;
  3172. this.z = source.z;
  3173. return this;
  3174. };
  3175. /**
  3176. * Copies the given floats to the current Vector3 coordinates
  3177. * @param x defines the x coordinate of the operand
  3178. * @param y defines the y coordinate of the operand
  3179. * @param z defines the z coordinate of the operand
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3183. this.x = x;
  3184. this.y = y;
  3185. this.z = z;
  3186. return this;
  3187. };
  3188. /**
  3189. * Copies the given floats to the current Vector3 coordinates
  3190. * @param x defines the x coordinate of the operand
  3191. * @param y defines the y coordinate of the operand
  3192. * @param z defines the z coordinate of the operand
  3193. * @returns the current updated Vector3
  3194. */
  3195. Vector3.prototype.set = function (x, y, z) {
  3196. return this.copyFromFloats(x, y, z);
  3197. };
  3198. // Statics
  3199. /**
  3200. * Get the clip factor between two vectors
  3201. * @param vector0 defines the first operand
  3202. * @param vector1 defines the second operand
  3203. * @param axis defines the axis to use
  3204. * @param size defines the size along the axis
  3205. * @returns the clip factor
  3206. */
  3207. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3208. var d0 = Vector3.Dot(vector0, axis) - size;
  3209. var d1 = Vector3.Dot(vector1, axis) - size;
  3210. var s = d0 / (d0 - d1);
  3211. return s;
  3212. };
  3213. /**
  3214. * Get angle between two vectors
  3215. * @param vector0 angle between vector0 and vector1
  3216. * @param vector1 angle between vector0 and vector1
  3217. * @param normal direction of the normal
  3218. * @return the angle between vector0 and vector1
  3219. */
  3220. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3221. var v0 = vector0.clone().normalize();
  3222. var v1 = vector1.clone().normalize();
  3223. var dot = Vector3.Dot(v0, v1);
  3224. var n = Vector3.Cross(v0, v1);
  3225. if (Vector3.Dot(n, normal) > 0) {
  3226. return Math.acos(dot);
  3227. }
  3228. return -Math.acos(dot);
  3229. };
  3230. /**
  3231. * Returns a new Vector3 set from the index "offset" of the given array
  3232. * @param array defines the source array
  3233. * @param offset defines the offset in the source array
  3234. * @returns the new Vector3
  3235. */
  3236. Vector3.FromArray = function (array, offset) {
  3237. if (!offset) {
  3238. offset = 0;
  3239. }
  3240. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3241. };
  3242. /**
  3243. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3244. * This function is deprecated. Use FromArray instead
  3245. * @param array defines the source array
  3246. * @param offset defines the offset in the source array
  3247. * @returns the new Vector3
  3248. */
  3249. Vector3.FromFloatArray = function (array, offset) {
  3250. return Vector3.FromArray(array, offset);
  3251. };
  3252. /**
  3253. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3254. * @param array defines the source array
  3255. * @param offset defines the offset in the source array
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.FromArrayToRef = function (array, offset, result) {
  3259. result.x = array[offset];
  3260. result.y = array[offset + 1];
  3261. result.z = array[offset + 2];
  3262. };
  3263. /**
  3264. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3265. * This function is deprecated. Use FromArrayToRef instead.
  3266. * @param array defines the source array
  3267. * @param offset defines the offset in the source array
  3268. * @param result defines the Vector3 where to store the result
  3269. */
  3270. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3271. return Vector3.FromArrayToRef(array, offset, result);
  3272. };
  3273. /**
  3274. * Sets the given vector "result" with the given floats.
  3275. * @param x defines the x coordinate of the source
  3276. * @param y defines the y coordinate of the source
  3277. * @param z defines the z coordinate of the source
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3281. result.x = x;
  3282. result.y = y;
  3283. result.z = z;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3287. * @returns a new empty Vector3
  3288. */
  3289. Vector3.Zero = function () {
  3290. return new Vector3(0.0, 0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3294. * @returns a new unit Vector3
  3295. */
  3296. Vector3.One = function () {
  3297. return new Vector3(1.0, 1.0, 1.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3301. * @returns a new up Vector3
  3302. */
  3303. Vector3.Up = function () {
  3304. return new Vector3(0.0, 1.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3308. * @returns a new forward Vector3
  3309. */
  3310. Vector3.Forward = function () {
  3311. return new Vector3(0.0, 0.0, 1.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3315. * @returns a new right Vector3
  3316. */
  3317. Vector3.Right = function () {
  3318. return new Vector3(1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3322. * @returns a new left Vector3
  3323. */
  3324. Vector3.Left = function () {
  3325. return new Vector3(-1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3329. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3330. * @param vector defines the Vector3 to transform
  3331. * @param transformation defines the transformation matrix
  3332. * @returns the transformed Vector3
  3333. */
  3334. Vector3.TransformCoordinates = function (vector, transformation) {
  3335. var result = Vector3.Zero();
  3336. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3337. return result;
  3338. };
  3339. /**
  3340. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @param result defines the Vector3 where to store the result
  3345. */
  3346. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3347. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3348. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3349. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3350. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3351. result.x = x / w;
  3352. result.y = y / w;
  3353. result.z = z / w;
  3354. };
  3355. /**
  3356. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3357. * This method computes tranformed coordinates only, not transformed direction vectors
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3366. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3367. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3368. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3369. result.x = rx / rw;
  3370. result.y = ry / rw;
  3371. result.z = rz / rw;
  3372. };
  3373. /**
  3374. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3375. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3376. * @param vector defines the Vector3 to transform
  3377. * @param transformation defines the transformation matrix
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.TransformNormal = function (vector, transformation) {
  3381. var result = Vector3.Zero();
  3382. Vector3.TransformNormalToRef(vector, transformation, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @param result defines the Vector3 where to store the result
  3391. */
  3392. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3395. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3396. result.x = x;
  3397. result.y = y;
  3398. result.z = z;
  3399. };
  3400. /**
  3401. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param x define the x coordinate of the source vector
  3404. * @param y define the y coordinate of the source vector
  3405. * @param z define the z coordinate of the source vector
  3406. * @param transformation defines the transformation matrix
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3410. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3411. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3412. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3416. * @param value1 defines the first control point
  3417. * @param value2 defines the second control point
  3418. * @param value3 defines the third control point
  3419. * @param value4 defines the fourth control point
  3420. * @param amount defines the amount on the spline to use
  3421. * @returns the new Vector3
  3422. */
  3423. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3424. var squared = amount * amount;
  3425. var cubed = amount * squared;
  3426. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3427. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3428. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3429. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3430. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3431. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3432. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3433. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3434. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * 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"
  3439. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3440. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3441. * @param value defines the current value
  3442. * @param min defines the lower range value
  3443. * @param max defines the upper range value
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.Clamp = function (value, min, max) {
  3447. var x = value.x;
  3448. x = (x > max.x) ? max.x : x;
  3449. x = (x < min.x) ? min.x : x;
  3450. var y = value.y;
  3451. y = (y > max.y) ? max.y : y;
  3452. y = (y < min.y) ? min.y : y;
  3453. var z = value.z;
  3454. z = (z > max.z) ? max.z : z;
  3455. z = (z < min.z) ? min.z : z;
  3456. return new Vector3(x, y, z);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3460. * @param value1 defines the first control point
  3461. * @param tangent1 defines the first tangent vector
  3462. * @param value2 defines the second control point
  3463. * @param tangent2 defines the second tangent vector
  3464. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3468. var squared = amount * amount;
  3469. var cubed = amount * squared;
  3470. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3471. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3472. var part3 = (cubed - (2.0 * squared)) + amount;
  3473. var part4 = cubed - squared;
  3474. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3475. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3476. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3477. return new Vector3(x, y, z);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3481. * @param start defines the start value
  3482. * @param end defines the end value
  3483. * @param amount max defines amount between both (between 0 and 1)
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.Lerp = function (start, end, amount) {
  3487. var result = new Vector3(0, 0, 0);
  3488. Vector3.LerpToRef(start, end, amount, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.LerpToRef = function (start, end, amount, result) {
  3499. result.x = start.x + ((end.x - start.x) * amount);
  3500. result.y = start.y + ((end.y - start.y) * amount);
  3501. result.z = start.z + ((end.z - start.z) * amount);
  3502. };
  3503. /**
  3504. * Returns the dot product (float) between the vectors "left" and "right"
  3505. * @param left defines the left operand
  3506. * @param right defines the right operand
  3507. * @returns the dot product
  3508. */
  3509. Vector3.Dot = function (left, right) {
  3510. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3511. };
  3512. /**
  3513. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3514. * The cross product is then orthogonal to both "left" and "right"
  3515. * @param left defines the left operand
  3516. * @param right defines the right operand
  3517. * @returns the cross product
  3518. */
  3519. Vector3.Cross = function (left, right) {
  3520. var result = Vector3.Zero();
  3521. Vector3.CrossToRef(left, right, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" with the cross product of "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @param result defines the Vector3 where to store the result
  3530. */
  3531. Vector3.CrossToRef = function (left, right, result) {
  3532. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3533. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3534. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3535. result.copyFrom(MathTmp.Vector3[0]);
  3536. };
  3537. /**
  3538. * Returns a new Vector3 as the normalization of the given vector
  3539. * @param vector defines the Vector3 to normalize
  3540. * @returns the new Vector3
  3541. */
  3542. Vector3.Normalize = function (vector) {
  3543. var result = Vector3.Zero();
  3544. Vector3.NormalizeToRef(vector, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the normalization of the given first vector
  3549. * @param vector defines the Vector3 to normalize
  3550. * @param result defines the Vector3 where to store the result
  3551. */
  3552. Vector3.NormalizeToRef = function (vector, result) {
  3553. result.copyFrom(vector);
  3554. result.normalize();
  3555. };
  3556. /**
  3557. * Project a Vector3 onto screen space
  3558. * @param vector defines the Vector3 to project
  3559. * @param world defines the world matrix to use
  3560. * @param transform defines the transform (view x projection) matrix to use
  3561. * @param viewport defines the screen viewport to use
  3562. * @returns the new Vector3
  3563. */
  3564. Vector3.Project = function (vector, world, transform, viewport) {
  3565. var cw = viewport.width;
  3566. var ch = viewport.height;
  3567. var cx = viewport.x;
  3568. var cy = viewport.y;
  3569. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3570. 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);
  3571. var matrix = MathTmp.Matrix[0];
  3572. world.multiplyToRef(transform, matrix);
  3573. matrix.multiplyToRef(viewportMatrix, matrix);
  3574. return Vector3.TransformCoordinates(vector, matrix);
  3575. };
  3576. /**
  3577. * Unproject from screen space to object space
  3578. * @param source defines the screen space Vector3 to use
  3579. * @param viewportWidth defines the current width of the viewport
  3580. * @param viewportHeight defines the current height of the viewport
  3581. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3582. * @param transform defines the transform (view x projection) matrix to use
  3583. * @returns the new Vector3
  3584. */
  3585. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3586. var matrix = MathTmp.Matrix[0];
  3587. world.multiplyToRef(transform, matrix);
  3588. matrix.invert();
  3589. source.x = source.x / viewportWidth * 2 - 1;
  3590. source.y = -(source.y / viewportHeight * 2 - 1);
  3591. var vector = Vector3.TransformCoordinates(source, matrix);
  3592. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3593. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3594. vector = vector.scale(1.0 / num);
  3595. }
  3596. return vector;
  3597. };
  3598. /**
  3599. * Unproject from screen space to object space
  3600. * @param source defines the screen space Vector3 to use
  3601. * @param viewportWidth defines the current width of the viewport
  3602. * @param viewportHeight defines the current height of the viewport
  3603. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3604. * @param view defines the view matrix to use
  3605. * @param projection defines the projection matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3609. var result = Vector3.Zero();
  3610. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Unproject from screen space to object space
  3615. * @param source defines the screen space Vector3 to use
  3616. * @param viewportWidth defines the current width of the viewport
  3617. * @param viewportHeight defines the current height of the viewport
  3618. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3619. * @param view defines the view matrix to use
  3620. * @param projection defines the projection matrix to use
  3621. * @param result defines the Vector3 where to store the result
  3622. */
  3623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3625. };
  3626. /**
  3627. * Unproject from screen space to object space
  3628. * @param sourceX defines the screen space x coordinate to use
  3629. * @param sourceY defines the screen space y coordinate to use
  3630. * @param sourceZ defines the screen space z coordinate to use
  3631. * @param viewportWidth defines the current width of the viewport
  3632. * @param viewportHeight defines the current height of the viewport
  3633. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3634. * @param view defines the view matrix to use
  3635. * @param projection defines the projection matrix to use
  3636. * @param result defines the Vector3 where to store the result
  3637. */
  3638. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3639. var matrix = MathTmp.Matrix[0];
  3640. world.multiplyToRef(view, matrix);
  3641. matrix.multiplyToRef(projection, matrix);
  3642. matrix.invert();
  3643. var screenSource = MathTmp.Vector3[0];
  3644. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3645. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3646. screenSource.z = 2 * sourceZ - 1.0;
  3647. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3648. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3649. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3650. result.scaleInPlace(1.0 / num);
  3651. }
  3652. };
  3653. /**
  3654. * Gets the minimal coordinate values between two Vector3
  3655. * @param left defines the first operand
  3656. * @param right defines the second operand
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Minimize = function (left, right) {
  3660. var min = left.clone();
  3661. min.minimizeInPlace(right);
  3662. return min;
  3663. };
  3664. /**
  3665. * Gets the maximal coordinate values between two Vector3
  3666. * @param left defines the first operand
  3667. * @param right defines the second operand
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Maximize = function (left, right) {
  3671. var max = left.clone();
  3672. max.maximizeInPlace(right);
  3673. return max;
  3674. };
  3675. /**
  3676. * Returns the distance between the vectors "value1" and "value2"
  3677. * @param value1 defines the first operand
  3678. * @param value2 defines the second operand
  3679. * @returns the distance
  3680. */
  3681. Vector3.Distance = function (value1, value2) {
  3682. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3683. };
  3684. /**
  3685. * Returns the squared distance between the vectors "value1" and "value2"
  3686. * @param value1 defines the first operand
  3687. * @param value2 defines the second operand
  3688. * @returns the squared distance
  3689. */
  3690. Vector3.DistanceSquared = function (value1, value2) {
  3691. var x = value1.x - value2.x;
  3692. var y = value1.y - value2.y;
  3693. var z = value1.z - value2.z;
  3694. return (x * x) + (y * y) + (z * z);
  3695. };
  3696. /**
  3697. * Returns a new Vector3 located at the center between "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the new Vector3
  3701. */
  3702. Vector3.Center = function (value1, value2) {
  3703. var center = value1.add(value2);
  3704. center.scaleInPlace(0.5);
  3705. return center;
  3706. };
  3707. /**
  3708. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3709. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3710. * to something in order to rotate it from its local system to the given target system
  3711. * Note: axis1, axis2 and axis3 are normalized during this operation
  3712. * @param axis1 defines the first axis
  3713. * @param axis2 defines the second axis
  3714. * @param axis3 defines the third axis
  3715. * @returns a new Vector3
  3716. */
  3717. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3718. var rotation = Vector3.Zero();
  3719. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3720. return rotation;
  3721. };
  3722. /**
  3723. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @param ref defines the Vector3 where to store the result
  3728. */
  3729. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3730. var quat = MathTmp.Quaternion[0];
  3731. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3732. quat.toEulerAnglesToRef(ref);
  3733. };
  3734. return Vector3;
  3735. }());
  3736. BABYLON.Vector3 = Vector3;
  3737. //Vector4 class created for EulerAngle class conversion to Quaternion
  3738. var Vector4 = /** @class */ (function () {
  3739. /**
  3740. * Creates a Vector4 object from the given floats.
  3741. */
  3742. function Vector4(x, y, z, w) {
  3743. this.x = x;
  3744. this.y = y;
  3745. this.z = z;
  3746. this.w = w;
  3747. }
  3748. /**
  3749. * Returns the string with the Vector4 coordinates.
  3750. */
  3751. Vector4.prototype.toString = function () {
  3752. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3753. };
  3754. /**
  3755. * Returns the string "Vector4".
  3756. */
  3757. Vector4.prototype.getClassName = function () {
  3758. return "Vector4";
  3759. };
  3760. /**
  3761. * Returns the Vector4 hash code.
  3762. */
  3763. Vector4.prototype.getHashCode = function () {
  3764. var hash = this.x || 0;
  3765. hash = (hash * 397) ^ (this.y || 0);
  3766. hash = (hash * 397) ^ (this.z || 0);
  3767. hash = (hash * 397) ^ (this.w || 0);
  3768. return hash;
  3769. };
  3770. // Operators
  3771. /**
  3772. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.asArray = function () {
  3775. var result = new Array();
  3776. this.toArray(result, 0);
  3777. return result;
  3778. };
  3779. /**
  3780. * Populates the given array from the given index with the Vector4 coordinates.
  3781. * Returns the Vector4.
  3782. */
  3783. Vector4.prototype.toArray = function (array, index) {
  3784. if (index === undefined) {
  3785. index = 0;
  3786. }
  3787. array[index] = this.x;
  3788. array[index + 1] = this.y;
  3789. array[index + 2] = this.z;
  3790. array[index + 3] = this.w;
  3791. return this;
  3792. };
  3793. /**
  3794. * Adds the given vector to the current Vector4.
  3795. * Returns the updated Vector4.
  3796. */
  3797. Vector4.prototype.addInPlace = function (otherVector) {
  3798. this.x += otherVector.x;
  3799. this.y += otherVector.y;
  3800. this.z += otherVector.z;
  3801. this.w += otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3806. */
  3807. Vector4.prototype.add = function (otherVector) {
  3808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3809. };
  3810. /**
  3811. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.addToRef = function (otherVector, result) {
  3815. result.x = this.x + otherVector.x;
  3816. result.y = this.y + otherVector.y;
  3817. result.z = this.z + otherVector.z;
  3818. result.w = this.w + otherVector.w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Subtract in place the given vector from the current Vector4.
  3823. * Returns the updated Vector4.
  3824. */
  3825. Vector4.prototype.subtractInPlace = function (otherVector) {
  3826. this.x -= otherVector.x;
  3827. this.y -= otherVector.y;
  3828. this.z -= otherVector.z;
  3829. this.w -= otherVector.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3834. */
  3835. Vector4.prototype.subtract = function (otherVector) {
  3836. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3837. };
  3838. /**
  3839. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3843. result.x = this.x - otherVector.x;
  3844. result.y = this.y - otherVector.y;
  3845. result.z = this.z - otherVector.z;
  3846. result.w = this.w - otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3851. */
  3852. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3853. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3854. };
  3855. /**
  3856. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3857. * Returns the current Vector4.
  3858. */
  3859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3860. result.x = this.x - x;
  3861. result.y = this.y - y;
  3862. result.z = this.z - z;
  3863. result.w = this.w - w;
  3864. return this;
  3865. };
  3866. /**
  3867. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3868. */
  3869. Vector4.prototype.negate = function () {
  3870. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3871. };
  3872. /**
  3873. * Multiplies the current Vector4 coordinates by scale (float).
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.scaleInPlace = function (scale) {
  3877. this.x *= scale;
  3878. this.y *= scale;
  3879. this.z *= scale;
  3880. this.w *= scale;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3885. */
  3886. Vector4.prototype.scale = function (scale) {
  3887. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3888. };
  3889. /**
  3890. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3891. * Returns the current Vector4.
  3892. */
  3893. Vector4.prototype.scaleToRef = function (scale, result) {
  3894. result.x = this.x * scale;
  3895. result.y = this.y * scale;
  3896. result.z = this.z * scale;
  3897. result.w = this.w * scale;
  3898. return this;
  3899. };
  3900. /**
  3901. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3902. * @param scale defines the scale factor
  3903. * @param result defines the Vector4 object where to store the result
  3904. * @returns the unmodified current Vector4
  3905. */
  3906. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3907. result.x += this.x * scale;
  3908. result.y += this.y * scale;
  3909. result.z += this.z * scale;
  3910. result.w += this.w * scale;
  3911. return this;
  3912. };
  3913. /**
  3914. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3915. */
  3916. Vector4.prototype.equals = function (otherVector) {
  3917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3918. };
  3919. /**
  3920. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3921. */
  3922. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3923. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3924. return otherVector
  3925. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3926. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3927. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3928. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3929. };
  3930. /**
  3931. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3932. */
  3933. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3934. return this.x === x && this.y === y && this.z === z && this.w === w;
  3935. };
  3936. /**
  3937. * Multiplies in place the current Vector4 by the given one.
  3938. * Returns the updated Vector4.
  3939. */
  3940. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3941. this.x *= otherVector.x;
  3942. this.y *= otherVector.y;
  3943. this.z *= otherVector.z;
  3944. this.w *= otherVector.w;
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3949. */
  3950. Vector4.prototype.multiply = function (otherVector) {
  3951. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3952. };
  3953. /**
  3954. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3955. * Returns the current Vector4.
  3956. */
  3957. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3958. result.x = this.x * otherVector.x;
  3959. result.y = this.y * otherVector.y;
  3960. result.z = this.z * otherVector.z;
  3961. result.w = this.w * otherVector.w;
  3962. return this;
  3963. };
  3964. /**
  3965. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3966. */
  3967. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3968. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3972. */
  3973. Vector4.prototype.divide = function (otherVector) {
  3974. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.divideToRef = function (otherVector, result) {
  3981. result.x = this.x / otherVector.x;
  3982. result.y = this.y / otherVector.y;
  3983. result.z = this.z / otherVector.z;
  3984. result.w = this.w / otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Divides the current Vector3 coordinates by the given ones.
  3989. * @returns the updated Vector3.
  3990. */
  3991. Vector4.prototype.divideInPlace = function (otherVector) {
  3992. return this.divideToRef(otherVector, this);
  3993. };
  3994. /**
  3995. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3996. * @param other defines the second operand
  3997. * @returns the current updated Vector4
  3998. */
  3999. Vector4.prototype.minimizeInPlace = function (other) {
  4000. if (other.x < this.x)
  4001. this.x = other.x;
  4002. if (other.y < this.y)
  4003. this.y = other.y;
  4004. if (other.z < this.z)
  4005. this.z = other.z;
  4006. if (other.w < this.w)
  4007. this.w = other.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4012. * @param other defines the second operand
  4013. * @returns the current updated Vector4
  4014. */
  4015. Vector4.prototype.maximizeInPlace = function (other) {
  4016. if (other.x > this.x)
  4017. this.x = other.x;
  4018. if (other.y > this.y)
  4019. this.y = other.y;
  4020. if (other.z > this.z)
  4021. this.z = other.z;
  4022. if (other.w > this.w)
  4023. this.w = other.w;
  4024. return this;
  4025. };
  4026. // Properties
  4027. /**
  4028. * Returns the Vector4 length (float).
  4029. */
  4030. Vector4.prototype.length = function () {
  4031. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4032. };
  4033. /**
  4034. * Returns the Vector4 squared length (float).
  4035. */
  4036. Vector4.prototype.lengthSquared = function () {
  4037. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4038. };
  4039. // Methods
  4040. /**
  4041. * Normalizes in place the Vector4.
  4042. * Returns the updated Vector4.
  4043. */
  4044. Vector4.prototype.normalize = function () {
  4045. var len = this.length();
  4046. if (len === 0)
  4047. return this;
  4048. var num = 1.0 / len;
  4049. this.x *= num;
  4050. this.y *= num;
  4051. this.z *= num;
  4052. this.w *= num;
  4053. return this;
  4054. };
  4055. /**
  4056. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4057. */
  4058. Vector4.prototype.toVector3 = function () {
  4059. return new Vector3(this.x, this.y, this.z);
  4060. };
  4061. /**
  4062. * Returns a new Vector4 copied from the current one.
  4063. */
  4064. Vector4.prototype.clone = function () {
  4065. return new Vector4(this.x, this.y, this.z, this.w);
  4066. };
  4067. /**
  4068. * Updates the current Vector4 with the given one coordinates.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.copyFrom = function (source) {
  4072. this.x = source.x;
  4073. this.y = source.y;
  4074. this.z = source.z;
  4075. this.w = source.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Updates the current Vector4 coordinates with the given floats.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4083. this.x = x;
  4084. this.y = y;
  4085. this.z = z;
  4086. this.w = w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Updates the current Vector4 coordinates with the given floats.
  4091. * Returns the updated Vector4.
  4092. */
  4093. Vector4.prototype.set = function (x, y, z, w) {
  4094. return this.copyFromFloats(x, y, z, w);
  4095. };
  4096. // Statics
  4097. /**
  4098. * Returns a new Vector4 set from the starting index of the given array.
  4099. */
  4100. Vector4.FromArray = function (array, offset) {
  4101. if (!offset) {
  4102. offset = 0;
  4103. }
  4104. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4105. };
  4106. /**
  4107. * Updates the given vector "result" from the starting index of the given array.
  4108. */
  4109. Vector4.FromArrayToRef = function (array, offset, result) {
  4110. result.x = array[offset];
  4111. result.y = array[offset + 1];
  4112. result.z = array[offset + 2];
  4113. result.w = array[offset + 3];
  4114. };
  4115. /**
  4116. * Updates the given vector "result" from the starting index of the given Float32Array.
  4117. */
  4118. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4119. Vector4.FromArrayToRef(array, offset, result);
  4120. };
  4121. /**
  4122. * Updates the given vector "result" coordinates from the given floats.
  4123. */
  4124. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4125. result.x = x;
  4126. result.y = y;
  4127. result.z = z;
  4128. result.w = w;
  4129. };
  4130. /**
  4131. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4132. */
  4133. Vector4.Zero = function () {
  4134. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4135. };
  4136. /**
  4137. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4138. */
  4139. Vector4.One = function () {
  4140. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4141. };
  4142. /**
  4143. * Returns a new normalized Vector4 from the given one.
  4144. */
  4145. Vector4.Normalize = function (vector) {
  4146. var result = Vector4.Zero();
  4147. Vector4.NormalizeToRef(vector, result);
  4148. return result;
  4149. };
  4150. /**
  4151. * Updates the given vector "result" from the normalization of the given one.
  4152. */
  4153. Vector4.NormalizeToRef = function (vector, result) {
  4154. result.copyFrom(vector);
  4155. result.normalize();
  4156. };
  4157. Vector4.Minimize = function (left, right) {
  4158. var min = left.clone();
  4159. min.minimizeInPlace(right);
  4160. return min;
  4161. };
  4162. Vector4.Maximize = function (left, right) {
  4163. var max = left.clone();
  4164. max.maximizeInPlace(right);
  4165. return max;
  4166. };
  4167. /**
  4168. * Returns the distance (float) between the vectors "value1" and "value2".
  4169. */
  4170. Vector4.Distance = function (value1, value2) {
  4171. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4172. };
  4173. /**
  4174. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4175. */
  4176. Vector4.DistanceSquared = function (value1, value2) {
  4177. var x = value1.x - value2.x;
  4178. var y = value1.y - value2.y;
  4179. var z = value1.z - value2.z;
  4180. var w = value1.w - value2.w;
  4181. return (x * x) + (y * y) + (z * z) + (w * w);
  4182. };
  4183. /**
  4184. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4185. */
  4186. Vector4.Center = function (value1, value2) {
  4187. var center = value1.add(value2);
  4188. center.scaleInPlace(0.5);
  4189. return center;
  4190. };
  4191. /**
  4192. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4193. * This methods computes transformed normalized direction vectors only.
  4194. */
  4195. Vector4.TransformNormal = function (vector, transformation) {
  4196. var result = Vector4.Zero();
  4197. Vector4.TransformNormalToRef(vector, transformation, result);
  4198. return result;
  4199. };
  4200. /**
  4201. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4202. * This methods computes transformed normalized direction vectors only.
  4203. */
  4204. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4205. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4206. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4207. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4208. result.x = x;
  4209. result.y = y;
  4210. result.z = z;
  4211. result.w = vector.w;
  4212. };
  4213. /**
  4214. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4215. * This methods computes transformed normalized direction vectors only.
  4216. */
  4217. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4218. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4219. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4220. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4221. result.w = w;
  4222. };
  4223. return Vector4;
  4224. }());
  4225. BABYLON.Vector4 = Vector4;
  4226. var Size = /** @class */ (function () {
  4227. /**
  4228. * Creates a Size object from the given width and height (floats).
  4229. */
  4230. function Size(width, height) {
  4231. this.width = width;
  4232. this.height = height;
  4233. }
  4234. // Returns a string with the Size width and height.
  4235. Size.prototype.toString = function () {
  4236. return "{W: " + this.width + ", H: " + this.height + "}";
  4237. };
  4238. /**
  4239. * Returns the string "Size"
  4240. */
  4241. Size.prototype.getClassName = function () {
  4242. return "Size";
  4243. };
  4244. /**
  4245. * Returns the Size hash code.
  4246. */
  4247. Size.prototype.getHashCode = function () {
  4248. var hash = this.width || 0;
  4249. hash = (hash * 397) ^ (this.height || 0);
  4250. return hash;
  4251. };
  4252. /**
  4253. * Updates the current size from the given one.
  4254. * Returns the updated Size.
  4255. */
  4256. Size.prototype.copyFrom = function (src) {
  4257. this.width = src.width;
  4258. this.height = src.height;
  4259. };
  4260. /**
  4261. * Updates in place the current Size from the given floats.
  4262. * Returns the updated Size.
  4263. */
  4264. Size.prototype.copyFromFloats = function (width, height) {
  4265. this.width = width;
  4266. this.height = height;
  4267. return this;
  4268. };
  4269. /**
  4270. * Updates in place the current Size from the given floats.
  4271. * Returns the updated Size.
  4272. */
  4273. Size.prototype.set = function (width, height) {
  4274. return this.copyFromFloats(width, height);
  4275. };
  4276. /**
  4277. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4278. */
  4279. Size.prototype.multiplyByFloats = function (w, h) {
  4280. return new Size(this.width * w, this.height * h);
  4281. };
  4282. /**
  4283. * Returns a new Size copied from the given one.
  4284. */
  4285. Size.prototype.clone = function () {
  4286. return new Size(this.width, this.height);
  4287. };
  4288. /**
  4289. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4290. */
  4291. Size.prototype.equals = function (other) {
  4292. if (!other) {
  4293. return false;
  4294. }
  4295. return (this.width === other.width) && (this.height === other.height);
  4296. };
  4297. Object.defineProperty(Size.prototype, "surface", {
  4298. /**
  4299. * Returns the surface of the Size : width * height (float).
  4300. */
  4301. get: function () {
  4302. return this.width * this.height;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. /**
  4308. * Returns a new Size set to (0.0, 0.0)
  4309. */
  4310. Size.Zero = function () {
  4311. return new Size(0.0, 0.0);
  4312. };
  4313. /**
  4314. * Returns a new Size set as the addition result of the current Size and the given one.
  4315. */
  4316. Size.prototype.add = function (otherSize) {
  4317. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4322. */
  4323. Size.prototype.subtract = function (otherSize) {
  4324. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4325. return r;
  4326. };
  4327. /**
  4328. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4329. */
  4330. Size.Lerp = function (start, end, amount) {
  4331. var w = start.width + ((end.width - start.width) * amount);
  4332. var h = start.height + ((end.height - start.height) * amount);
  4333. return new Size(w, h);
  4334. };
  4335. return Size;
  4336. }());
  4337. BABYLON.Size = Size;
  4338. /**
  4339. * Class used to store quaternion data
  4340. * @see https://en.wikipedia.org/wiki/Quaternion
  4341. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4342. */
  4343. var Quaternion = /** @class */ (function () {
  4344. /**
  4345. * Creates a new Quaternion from the given floats
  4346. * @param x defines the first component (0 by default)
  4347. * @param y defines the second component (0 by default)
  4348. * @param z defines the third component (0 by default)
  4349. * @param w defines the fourth component (1.0 by default)
  4350. */
  4351. function Quaternion(
  4352. /** defines the first component (0 by default) */
  4353. x,
  4354. /** defines the second component (0 by default) */
  4355. y,
  4356. /** defines the third component (0 by default) */
  4357. z,
  4358. /** defines the fourth component (1.0 by default) */
  4359. w) {
  4360. if (x === void 0) { x = 0.0; }
  4361. if (y === void 0) { y = 0.0; }
  4362. if (z === void 0) { z = 0.0; }
  4363. if (w === void 0) { w = 1.0; }
  4364. this.x = x;
  4365. this.y = y;
  4366. this.z = z;
  4367. this.w = w;
  4368. }
  4369. /**
  4370. * Gets a string representation for the current quaternion
  4371. * @returns a string with the Quaternion coordinates
  4372. */
  4373. Quaternion.prototype.toString = function () {
  4374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4375. };
  4376. /**
  4377. * Gets the class name of the quaternion
  4378. * @returns the string "Quaternion"
  4379. */
  4380. Quaternion.prototype.getClassName = function () {
  4381. return "Quaternion";
  4382. };
  4383. /**
  4384. * Gets a hash code for this quaternion
  4385. * @returns the quaternion hash code
  4386. */
  4387. Quaternion.prototype.getHashCode = function () {
  4388. var hash = this.x || 0;
  4389. hash = (hash * 397) ^ (this.y || 0);
  4390. hash = (hash * 397) ^ (this.z || 0);
  4391. hash = (hash * 397) ^ (this.w || 0);
  4392. return hash;
  4393. };
  4394. /**
  4395. * Copy the quaternion to an array
  4396. * @returns a new array populated with 4 elements from the quaternion coordinates
  4397. */
  4398. Quaternion.prototype.asArray = function () {
  4399. return [this.x, this.y, this.z, this.w];
  4400. };
  4401. /**
  4402. * Check if two quaternions are equals
  4403. * @param otherQuaternion defines the second operand
  4404. * @return true if the current quaternion and the given one coordinates are strictly equals
  4405. */
  4406. Quaternion.prototype.equals = function (otherQuaternion) {
  4407. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4408. };
  4409. /**
  4410. * Clone the current quaternion
  4411. * @returns a new quaternion copied from the current one
  4412. */
  4413. Quaternion.prototype.clone = function () {
  4414. return new Quaternion(this.x, this.y, this.z, this.w);
  4415. };
  4416. /**
  4417. * Copy a quaternion to the current one
  4418. * @param other defines the other quaternion
  4419. * @returns the updated current quaternion
  4420. */
  4421. Quaternion.prototype.copyFrom = function (other) {
  4422. this.x = other.x;
  4423. this.y = other.y;
  4424. this.z = other.z;
  4425. this.w = other.w;
  4426. return this;
  4427. };
  4428. /**
  4429. * Updates the current quaternion with the given float coordinates
  4430. * @param x defines the x coordinate
  4431. * @param y defines the y coordinate
  4432. * @param z defines the z coordinate
  4433. * @param w defines the w coordinate
  4434. * @returns the updated current quaternion
  4435. */
  4436. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4437. this.x = x;
  4438. this.y = y;
  4439. this.z = z;
  4440. this.w = w;
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current quaternion from the given float coordinates
  4445. * @param x defines the x coordinate
  4446. * @param y defines the y coordinate
  4447. * @param z defines the z coordinate
  4448. * @param w defines the w coordinate
  4449. * @returns the updated current quaternion
  4450. */
  4451. Quaternion.prototype.set = function (x, y, z, w) {
  4452. return this.copyFromFloats(x, y, z, w);
  4453. };
  4454. /**
  4455. * Adds two quaternions
  4456. * @param other defines the second operand
  4457. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4458. */
  4459. Quaternion.prototype.add = function (other) {
  4460. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4461. };
  4462. /**
  4463. * Add a quaternion to the current one
  4464. * @param other defines the quaternion to add
  4465. * @returns the current quaternion
  4466. */
  4467. Quaternion.prototype.addInPlace = function (other) {
  4468. this.x += other.x;
  4469. this.y += other.y;
  4470. this.z += other.z;
  4471. this.w += other.w;
  4472. return this;
  4473. };
  4474. /**
  4475. * Subtract two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the subtraction result of the given one from the current one
  4478. */
  4479. Quaternion.prototype.subtract = function (other) {
  4480. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4481. };
  4482. /**
  4483. * Multiplies the current quaternion by a scale factor
  4484. * @param value defines the scale factor
  4485. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4486. */
  4487. Quaternion.prototype.scale = function (value) {
  4488. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4489. };
  4490. /**
  4491. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current quaternion
  4495. */
  4496. Quaternion.prototype.scaleToRef = function (scale, result) {
  4497. result.x = this.x * scale;
  4498. result.y = this.y * scale;
  4499. result.z = this.z * scale;
  4500. result.w = this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Multiplies in place the current quaternion by a scale factor
  4505. * @param value defines the scale factor
  4506. * @returns the current modified quaternion
  4507. */
  4508. Quaternion.prototype.scaleInPlace = function (value) {
  4509. this.x *= value;
  4510. this.y *= value;
  4511. this.z *= value;
  4512. this.w *= value;
  4513. return this;
  4514. };
  4515. /**
  4516. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4517. * @param scale defines the scale factor
  4518. * @param result defines the Quaternion object where to store the result
  4519. * @returns the unmodified current quaternion
  4520. */
  4521. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4522. result.x += this.x * scale;
  4523. result.y += this.y * scale;
  4524. result.z += this.z * scale;
  4525. result.w += this.w * scale;
  4526. return this;
  4527. };
  4528. /**
  4529. * Multiplies two quaternions
  4530. * @param q1 defines the second operand
  4531. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4532. */
  4533. Quaternion.prototype.multiply = function (q1) {
  4534. var result = new Quaternion(0, 0, 0, 1.0);
  4535. this.multiplyToRef(q1, result);
  4536. return result;
  4537. };
  4538. /**
  4539. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4540. * @param q1 defines the second operand
  4541. * @param result defines the target quaternion
  4542. * @returns the current quaternion
  4543. */
  4544. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4545. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4546. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4547. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4548. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4549. result.copyFromFloats(x, y, z, w);
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4554. * @param q1 defines the second operand
  4555. * @returns the currentupdated quaternion
  4556. */
  4557. Quaternion.prototype.multiplyInPlace = function (q1) {
  4558. this.multiplyToRef(q1, this);
  4559. return this;
  4560. };
  4561. /**
  4562. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4563. * @param ref defines the target quaternion
  4564. * @returns the current quaternion
  4565. */
  4566. Quaternion.prototype.conjugateToRef = function (ref) {
  4567. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4568. return this;
  4569. };
  4570. /**
  4571. * Conjugates in place (1-q) the current quaternion
  4572. * @returns the current updated quaternion
  4573. */
  4574. Quaternion.prototype.conjugateInPlace = function () {
  4575. this.x *= -1;
  4576. this.y *= -1;
  4577. this.z *= -1;
  4578. return this;
  4579. };
  4580. /**
  4581. * Conjugates in place (1-q) the current quaternion
  4582. * @returns a new quaternion
  4583. */
  4584. Quaternion.prototype.conjugate = function () {
  4585. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4586. return result;
  4587. };
  4588. /**
  4589. * Gets length of current quaternion
  4590. * @returns the quaternion length (float)
  4591. */
  4592. Quaternion.prototype.length = function () {
  4593. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4594. };
  4595. /**
  4596. * Normalize in place the current quaternion
  4597. * @returns the current updated quaternion
  4598. */
  4599. Quaternion.prototype.normalize = function () {
  4600. var length = 1.0 / this.length();
  4601. this.x *= length;
  4602. this.y *= length;
  4603. this.z *= length;
  4604. this.w *= length;
  4605. return this;
  4606. };
  4607. /**
  4608. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4609. * @param order is a reserved parameter and is ignore for now
  4610. * @returns a new Vector3 containing the Euler angles
  4611. */
  4612. Quaternion.prototype.toEulerAngles = function (order) {
  4613. if (order === void 0) { order = "YZX"; }
  4614. var result = Vector3.Zero();
  4615. this.toEulerAnglesToRef(result, order);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4620. * @param result defines the vector which will be filled with the Euler angles
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns the current unchanged quaternion
  4623. */
  4624. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var qz = this.z;
  4627. var qx = this.x;
  4628. var qy = this.y;
  4629. var qw = this.w;
  4630. var sqw = qw * qw;
  4631. var sqz = qz * qz;
  4632. var sqx = qx * qx;
  4633. var sqy = qy * qy;
  4634. var zAxisY = qy * qz - qx * qw;
  4635. var limit = .4999999;
  4636. if (zAxisY < -limit) {
  4637. result.y = 2 * Math.atan2(qy, qw);
  4638. result.x = Math.PI / 2;
  4639. result.z = 0;
  4640. }
  4641. else if (zAxisY > limit) {
  4642. result.y = 2 * Math.atan2(qy, qw);
  4643. result.x = -Math.PI / 2;
  4644. result.z = 0;
  4645. }
  4646. else {
  4647. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4648. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4649. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4650. }
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the given rotation matrix with the current quaternion values
  4655. * @param result defines the target matrix
  4656. * @returns the current unchanged quaternion
  4657. */
  4658. Quaternion.prototype.toRotationMatrix = function (result) {
  4659. var xx = this.x * this.x;
  4660. var yy = this.y * this.y;
  4661. var zz = this.z * this.z;
  4662. var xy = this.x * this.y;
  4663. var zw = this.z * this.w;
  4664. var zx = this.z * this.x;
  4665. var yw = this.y * this.w;
  4666. var yz = this.y * this.z;
  4667. var xw = this.x * this.w;
  4668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4669. result.m[1] = 2.0 * (xy + zw);
  4670. result.m[2] = 2.0 * (zx - yw);
  4671. result.m[3] = 0;
  4672. result.m[4] = 2.0 * (xy - zw);
  4673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4674. result.m[6] = 2.0 * (yz + xw);
  4675. result.m[7] = 0;
  4676. result.m[8] = 2.0 * (zx + yw);
  4677. result.m[9] = 2.0 * (yz - xw);
  4678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4679. result.m[11] = 0;
  4680. result.m[12] = 0;
  4681. result.m[13] = 0;
  4682. result.m[14] = 0;
  4683. result.m[15] = 1.0;
  4684. result._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the current quaternion from the given rotation matrix values
  4689. * @param matrix defines the source matrix
  4690. * @returns the current updated quaternion
  4691. */
  4692. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4693. Quaternion.FromRotationMatrixToRef(matrix, this);
  4694. return this;
  4695. };
  4696. // Statics
  4697. /**
  4698. * Creates a new quaternion from a rotation matrix
  4699. * @param matrix defines the source matrix
  4700. * @returns a new quaternion created from the given rotation matrix values
  4701. */
  4702. Quaternion.FromRotationMatrix = function (matrix) {
  4703. var result = new Quaternion();
  4704. Quaternion.FromRotationMatrixToRef(matrix, result);
  4705. return result;
  4706. };
  4707. /**
  4708. * Updates the given quaternion with the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @param result defines the target quaternion
  4711. */
  4712. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4713. var data = matrix.m;
  4714. var m11 = data[0], m12 = data[4], m13 = data[8];
  4715. var m21 = data[1], m22 = data[5], m23 = data[9];
  4716. var m31 = data[2], m32 = data[6], m33 = data[10];
  4717. var trace = m11 + m22 + m33;
  4718. var s;
  4719. if (trace > 0) {
  4720. s = 0.5 / Math.sqrt(trace + 1.0);
  4721. result.w = 0.25 / s;
  4722. result.x = (m32 - m23) * s;
  4723. result.y = (m13 - m31) * s;
  4724. result.z = (m21 - m12) * s;
  4725. }
  4726. else if (m11 > m22 && m11 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4728. result.w = (m32 - m23) / s;
  4729. result.x = 0.25 * s;
  4730. result.y = (m12 + m21) / s;
  4731. result.z = (m13 + m31) / s;
  4732. }
  4733. else if (m22 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4735. result.w = (m13 - m31) / s;
  4736. result.x = (m12 + m21) / s;
  4737. result.y = 0.25 * s;
  4738. result.z = (m23 + m32) / s;
  4739. }
  4740. else {
  4741. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4742. result.w = (m21 - m12) / s;
  4743. result.x = (m13 + m31) / s;
  4744. result.y = (m23 + m32) / s;
  4745. result.z = 0.25 * s;
  4746. }
  4747. };
  4748. /**
  4749. * Returns the dot product (float) between the quaternions "left" and "right"
  4750. * @param left defines the left operand
  4751. * @param right defines the right operand
  4752. * @returns the dot product
  4753. */
  4754. Quaternion.Dot = function (left, right) {
  4755. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4756. };
  4757. /**
  4758. * Checks if the two quaternions are close to each other
  4759. * @param quat0 defines the first quaternion to check
  4760. * @param quat1 defines the second quaternion to check
  4761. * @returns true if the two quaternions are close to each other
  4762. */
  4763. Quaternion.AreClose = function (quat0, quat1) {
  4764. var dot = Quaternion.Dot(quat0, quat1);
  4765. return dot >= 0;
  4766. };
  4767. /**
  4768. * Creates an empty quaternion
  4769. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4770. */
  4771. Quaternion.Zero = function () {
  4772. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4773. };
  4774. /**
  4775. * Inverse a given quaternion
  4776. * @param q defines the source quaternion
  4777. * @returns a new quaternion as the inverted current quaternion
  4778. */
  4779. Quaternion.Inverse = function (q) {
  4780. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4781. };
  4782. /**
  4783. * Creates an identity quaternion
  4784. * @returns the identity quaternion
  4785. */
  4786. Quaternion.Identity = function () {
  4787. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4788. };
  4789. /**
  4790. * Gets a boolean indicating if the given quaternion is identity
  4791. * @param quaternion defines the quaternion to check
  4792. * @returns true if the quaternion is identity
  4793. */
  4794. Quaternion.IsIdentity = function (quaternion) {
  4795. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4796. };
  4797. /**
  4798. * Creates a quaternion from a rotation around an axis
  4799. * @param axis defines the axis to use
  4800. * @param angle defines the angle to use
  4801. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4802. */
  4803. Quaternion.RotationAxis = function (axis, angle) {
  4804. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4805. };
  4806. /**
  4807. * Creates a rotation around an axis and stores it into the given quaternion
  4808. * @param axis defines the axis to use
  4809. * @param angle defines the angle to use
  4810. * @param result defines the target quaternion
  4811. * @returns the target quaternion
  4812. */
  4813. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4814. var sin = Math.sin(angle / 2);
  4815. axis.normalize();
  4816. result.w = Math.cos(angle / 2);
  4817. result.x = axis.x * sin;
  4818. result.y = axis.y * sin;
  4819. result.z = axis.z * sin;
  4820. return result;
  4821. };
  4822. /**
  4823. * Creates a new quaternion from data stored into an array
  4824. * @param array defines the data source
  4825. * @param offset defines the offset in the source array where the data starts
  4826. * @returns a new quaternion
  4827. */
  4828. Quaternion.FromArray = function (array, offset) {
  4829. if (!offset) {
  4830. offset = 0;
  4831. }
  4832. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4833. };
  4834. /**
  4835. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4836. * @param yaw defines the rotation around Y axis
  4837. * @param pitch defines the rotation around X axis
  4838. * @param roll defines the rotation around Z axis
  4839. * @returns the new quaternion
  4840. */
  4841. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4842. var q = new Quaternion();
  4843. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4844. return q;
  4845. };
  4846. /**
  4847. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @param result defines the target quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4854. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4855. var halfRoll = roll * 0.5;
  4856. var halfPitch = pitch * 0.5;
  4857. var halfYaw = yaw * 0.5;
  4858. var sinRoll = Math.sin(halfRoll);
  4859. var cosRoll = Math.cos(halfRoll);
  4860. var sinPitch = Math.sin(halfPitch);
  4861. var cosPitch = Math.cos(halfPitch);
  4862. var sinYaw = Math.sin(halfYaw);
  4863. var cosYaw = Math.cos(halfYaw);
  4864. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4865. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4866. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4867. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4868. };
  4869. /**
  4870. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4871. * @param alpha defines the rotation around first axis
  4872. * @param beta defines the rotation around second axis
  4873. * @param gamma defines the rotation around third axis
  4874. * @returns the new quaternion
  4875. */
  4876. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4877. var result = new Quaternion();
  4878. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4879. return result;
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @param result defines the target quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4889. // Produces a quaternion from Euler angles in the z-x-z orientation
  4890. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4891. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4892. var halfBeta = beta * 0.5;
  4893. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4894. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4896. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. };
  4898. /**
  4899. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4900. * @param axis1 defines the first axis
  4901. * @param axis2 defines the second axis
  4902. * @param axis3 defines the third axis
  4903. * @returns the new quaternion
  4904. */
  4905. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4906. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4907. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4908. return quat;
  4909. };
  4910. /**
  4911. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @param ref defines the target quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4918. var rotMat = MathTmp.Matrix[0];
  4919. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4920. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4921. };
  4922. /**
  4923. * Interpolates between two quaternions
  4924. * @param left defines first quaternion
  4925. * @param right defines second quaternion
  4926. * @param amount defines the gradient to use
  4927. * @returns the new interpolated quaternion
  4928. */
  4929. Quaternion.Slerp = function (left, right, amount) {
  4930. var result = Quaternion.Identity();
  4931. Quaternion.SlerpToRef(left, right, amount, result);
  4932. return result;
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions and stores it into a target quaternion
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @param result defines the target quaternion
  4940. */
  4941. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4942. var num2;
  4943. var num3;
  4944. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4945. var flag = false;
  4946. if (num4 < 0) {
  4947. flag = true;
  4948. num4 = -num4;
  4949. }
  4950. if (num4 > 0.999999) {
  4951. num3 = 1 - amount;
  4952. num2 = flag ? -amount : amount;
  4953. }
  4954. else {
  4955. var num5 = Math.acos(num4);
  4956. var num6 = (1.0 / Math.sin(num5));
  4957. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4958. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4959. }
  4960. result.x = (num3 * left.x) + (num2 * right.x);
  4961. result.y = (num3 * left.y) + (num2 * right.y);
  4962. result.z = (num3 * left.z) + (num2 * right.z);
  4963. result.w = (num3 * left.w) + (num2 * right.w);
  4964. };
  4965. /**
  4966. * Interpolate between two quaternions using Hermite interpolation
  4967. * @param value1 defines first quaternion
  4968. * @param tangent1 defines the incoming tangent
  4969. * @param value2 defines second quaternion
  4970. * @param tangent2 defines the outgoing tangent
  4971. * @param amount defines the target quaternion
  4972. * @returns the new interpolated quaternion
  4973. */
  4974. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4975. var squared = amount * amount;
  4976. var cubed = amount * squared;
  4977. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4978. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4979. var part3 = (cubed - (2.0 * squared)) + amount;
  4980. var part4 = cubed - squared;
  4981. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4982. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4983. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4984. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4985. return new Quaternion(x, y, z, w);
  4986. };
  4987. return Quaternion;
  4988. }());
  4989. BABYLON.Quaternion = Quaternion;
  4990. /**
  4991. * Class used to store matrix data (4x4)
  4992. */
  4993. var Matrix = /** @class */ (function () {
  4994. /**
  4995. * Creates an empty matrix (filled with zeros)
  4996. */
  4997. function Matrix() {
  4998. this._isIdentity = false;
  4999. this._isIdentityDirty = true;
  5000. /**
  5001. * Gets or sets the internal data of the matrix
  5002. */
  5003. this.m = new Float32Array(16);
  5004. this._markAsUpdated();
  5005. }
  5006. /** @hidden */
  5007. Matrix.prototype._markAsUpdated = function () {
  5008. this.updateFlag = Matrix._updateFlagSeed++;
  5009. this._isIdentityDirty = true;
  5010. };
  5011. // Properties
  5012. /**
  5013. * Check if the current matrix is indentity
  5014. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5015. * @returns true is the matrix is the identity matrix
  5016. */
  5017. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5018. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5019. if (this._isIdentityDirty) {
  5020. this._isIdentityDirty = false;
  5021. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5022. this._isIdentity = false;
  5023. }
  5024. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5025. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5026. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5027. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5028. this._isIdentity = false;
  5029. }
  5030. else {
  5031. this._isIdentity = true;
  5032. }
  5033. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. }
  5037. return this._isIdentity;
  5038. };
  5039. /**
  5040. * Gets the determinant of the matrix
  5041. * @returns the matrix determinant
  5042. */
  5043. Matrix.prototype.determinant = function () {
  5044. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5045. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5046. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5047. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5048. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5049. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5050. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5051. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5052. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5053. };
  5054. // Methods
  5055. /**
  5056. * Returns the matrix as a Float32Array
  5057. * @returns the matrix underlying array
  5058. */
  5059. Matrix.prototype.toArray = function () {
  5060. return this.m;
  5061. };
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array.
  5065. */
  5066. Matrix.prototype.asArray = function () {
  5067. return this.toArray();
  5068. };
  5069. /**
  5070. * Inverts the current matrix in place
  5071. * @returns the current inverted matrix
  5072. */
  5073. Matrix.prototype.invert = function () {
  5074. this.invertToRef(this);
  5075. return this;
  5076. };
  5077. /**
  5078. * Sets all the matrix elements to zero
  5079. * @returns the current matrix
  5080. */
  5081. Matrix.prototype.reset = function () {
  5082. for (var index = 0; index < 16; index++) {
  5083. this.m[index] = 0.0;
  5084. }
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Adds the current matrix with a second one
  5090. * @param other defines the matrix to add
  5091. * @returns a new matrix as the addition of the current matrix and the given one
  5092. */
  5093. Matrix.prototype.add = function (other) {
  5094. var result = new Matrix();
  5095. this.addToRef(other, result);
  5096. return result;
  5097. };
  5098. /**
  5099. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5100. * @param other defines the matrix to add
  5101. * @param result defines the target matrix
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.addToRef = function (other, result) {
  5105. for (var index = 0; index < 16; index++) {
  5106. result.m[index] = this.m[index] + other.m[index];
  5107. }
  5108. result._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds in place the given matrix to the current matrix
  5113. * @param other defines the second operand
  5114. * @returns the current updated matrix
  5115. */
  5116. Matrix.prototype.addToSelf = function (other) {
  5117. for (var index = 0; index < 16; index++) {
  5118. this.m[index] += other.m[index];
  5119. }
  5120. this._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Sets the given matrix to the current inverted Matrix
  5125. * @param other defines the target matrix
  5126. * @returns the unmodified current matrix
  5127. */
  5128. Matrix.prototype.invertToRef = function (other) {
  5129. var l1 = this.m[0];
  5130. var l2 = this.m[1];
  5131. var l3 = this.m[2];
  5132. var l4 = this.m[3];
  5133. var l5 = this.m[4];
  5134. var l6 = this.m[5];
  5135. var l7 = this.m[6];
  5136. var l8 = this.m[7];
  5137. var l9 = this.m[8];
  5138. var l10 = this.m[9];
  5139. var l11 = this.m[10];
  5140. var l12 = this.m[11];
  5141. var l13 = this.m[12];
  5142. var l14 = this.m[13];
  5143. var l15 = this.m[14];
  5144. var l16 = this.m[15];
  5145. var l17 = (l11 * l16) - (l12 * l15);
  5146. var l18 = (l10 * l16) - (l12 * l14);
  5147. var l19 = (l10 * l15) - (l11 * l14);
  5148. var l20 = (l9 * l16) - (l12 * l13);
  5149. var l21 = (l9 * l15) - (l11 * l13);
  5150. var l22 = (l9 * l14) - (l10 * l13);
  5151. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5152. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5153. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5154. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5155. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5156. var l28 = (l7 * l16) - (l8 * l15);
  5157. var l29 = (l6 * l16) - (l8 * l14);
  5158. var l30 = (l6 * l15) - (l7 * l14);
  5159. var l31 = (l5 * l16) - (l8 * l13);
  5160. var l32 = (l5 * l15) - (l7 * l13);
  5161. var l33 = (l5 * l14) - (l6 * l13);
  5162. var l34 = (l7 * l12) - (l8 * l11);
  5163. var l35 = (l6 * l12) - (l8 * l10);
  5164. var l36 = (l6 * l11) - (l7 * l10);
  5165. var l37 = (l5 * l12) - (l8 * l9);
  5166. var l38 = (l5 * l11) - (l7 * l9);
  5167. var l39 = (l5 * l10) - (l6 * l9);
  5168. other.m[0] = l23 * l27;
  5169. other.m[4] = l24 * l27;
  5170. other.m[8] = l25 * l27;
  5171. other.m[12] = l26 * l27;
  5172. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5173. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5174. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5175. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5176. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5177. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5178. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5179. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5180. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5181. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5182. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5183. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5184. other._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Inserts the translation vector (using 3 floats) in the current matrix
  5189. * @param x defines the 1st component of the translation
  5190. * @param y defines the 2nd component of the translation
  5191. * @param z defines the 3rd component of the translation
  5192. * @returns the current updated matrix
  5193. */
  5194. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5195. this.m[12] = x;
  5196. this.m[13] = y;
  5197. this.m[14] = z;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Inserts the translation vector in the current matrix
  5203. * @param vector3 defines the translation to insert
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslation = function (vector3) {
  5207. this.m[12] = vector3.x;
  5208. this.m[13] = vector3.y;
  5209. this.m[14] = vector3.z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Gets the translation value of the current matrix
  5215. * @returns a new Vector3 as the extracted translation from the matrix
  5216. */
  5217. Matrix.prototype.getTranslation = function () {
  5218. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5219. };
  5220. /**
  5221. * Fill a Vector3 with the extracted translation from the matrix
  5222. * @param result defines the Vector3 where to store the translation
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.getTranslationToRef = function (result) {
  5226. result.x = this.m[12];
  5227. result.y = this.m[13];
  5228. result.z = this.m[14];
  5229. return this;
  5230. };
  5231. /**
  5232. * Remove rotation and scaling part from the matrix
  5233. * @returns the updated matrix
  5234. */
  5235. Matrix.prototype.removeRotationAndScaling = function () {
  5236. this.setRowFromFloats(0, 1, 0, 0, 0);
  5237. this.setRowFromFloats(1, 0, 1, 0, 0);
  5238. this.setRowFromFloats(2, 0, 0, 1, 0);
  5239. return this;
  5240. };
  5241. /**
  5242. * Multiply two matrices
  5243. * @param other defines the second operand
  5244. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5245. */
  5246. Matrix.prototype.multiply = function (other) {
  5247. var result = new Matrix();
  5248. this.multiplyToRef(other, result);
  5249. return result;
  5250. };
  5251. /**
  5252. * Copy the current matrix from the given one
  5253. * @param other defines the source matrix
  5254. * @returns the current updated matrix
  5255. */
  5256. Matrix.prototype.copyFrom = function (other) {
  5257. for (var index = 0; index < 16; index++) {
  5258. this.m[index] = other.m[index];
  5259. }
  5260. this._markAsUpdated();
  5261. return this;
  5262. };
  5263. /**
  5264. * Populates the given array from the starting index with the current matrix values
  5265. * @param array defines the target array
  5266. * @param offset defines the offset in the target array where to start storing values
  5267. * @returns the current matrix
  5268. */
  5269. Matrix.prototype.copyToArray = function (array, offset) {
  5270. if (offset === void 0) { offset = 0; }
  5271. for (var index = 0; index < 16; index++) {
  5272. array[offset + index] = this.m[index];
  5273. }
  5274. return this;
  5275. };
  5276. /**
  5277. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5278. * @param other defines the second operand
  5279. * @param result defines the matrix where to store the multiplication
  5280. * @returns the current matrix
  5281. */
  5282. Matrix.prototype.multiplyToRef = function (other, result) {
  5283. this.multiplyToArray(other, result.m, 0);
  5284. result._markAsUpdated();
  5285. return this;
  5286. };
  5287. /**
  5288. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5289. * @param other defines the second operand
  5290. * @param result defines the array where to store the multiplication
  5291. * @param offset defines the offset in the target array where to start storing values
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5295. var tm0 = this.m[0];
  5296. var tm1 = this.m[1];
  5297. var tm2 = this.m[2];
  5298. var tm3 = this.m[3];
  5299. var tm4 = this.m[4];
  5300. var tm5 = this.m[5];
  5301. var tm6 = this.m[6];
  5302. var tm7 = this.m[7];
  5303. var tm8 = this.m[8];
  5304. var tm9 = this.m[9];
  5305. var tm10 = this.m[10];
  5306. var tm11 = this.m[11];
  5307. var tm12 = this.m[12];
  5308. var tm13 = this.m[13];
  5309. var tm14 = this.m[14];
  5310. var tm15 = this.m[15];
  5311. var om0 = other.m[0];
  5312. var om1 = other.m[1];
  5313. var om2 = other.m[2];
  5314. var om3 = other.m[3];
  5315. var om4 = other.m[4];
  5316. var om5 = other.m[5];
  5317. var om6 = other.m[6];
  5318. var om7 = other.m[7];
  5319. var om8 = other.m[8];
  5320. var om9 = other.m[9];
  5321. var om10 = other.m[10];
  5322. var om11 = other.m[11];
  5323. var om12 = other.m[12];
  5324. var om13 = other.m[13];
  5325. var om14 = other.m[14];
  5326. var om15 = other.m[15];
  5327. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5328. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5329. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5330. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5331. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5332. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5333. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5334. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5335. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5336. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5337. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5338. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5339. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5340. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5341. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5342. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5343. return this;
  5344. };
  5345. /**
  5346. * Check equality between this matrix and a second one
  5347. * @param value defines the second matrix to compare
  5348. * @returns true is the current matrix and the given one values are strictly equal
  5349. */
  5350. Matrix.prototype.equals = function (value) {
  5351. return value &&
  5352. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5353. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5354. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5355. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5356. };
  5357. /**
  5358. * Clone the current matrix
  5359. * @returns a new matrix from the current matrix
  5360. */
  5361. Matrix.prototype.clone = function () {
  5362. 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]);
  5363. };
  5364. /**
  5365. * Returns the name of the current matrix class
  5366. * @returns the string "Matrix"
  5367. */
  5368. Matrix.prototype.getClassName = function () {
  5369. return "Matrix";
  5370. };
  5371. /**
  5372. * Gets the hash code of the current matrix
  5373. * @returns the hash code
  5374. */
  5375. Matrix.prototype.getHashCode = function () {
  5376. var hash = this.m[0] || 0;
  5377. for (var i = 1; i < 16; i++) {
  5378. hash = (hash * 397) ^ (this.m[i] || 0);
  5379. }
  5380. return hash;
  5381. };
  5382. /**
  5383. * Decomposes the current Matrix into a translation, rotation and scaling components
  5384. * @param scale defines the scale vector3 given as a reference to update
  5385. * @param rotation defines the rotation quaternion given as a reference to update
  5386. * @param translation defines the translation vector3 given as a reference to update
  5387. * @returns true if operation was successful
  5388. */
  5389. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5390. if (translation) {
  5391. translation.x = this.m[12];
  5392. translation.y = this.m[13];
  5393. translation.z = this.m[14];
  5394. }
  5395. scale = scale || MathTmp.Vector3[0];
  5396. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5397. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5398. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5399. if (this.determinant() <= 0) {
  5400. scale.y *= -1;
  5401. }
  5402. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5403. if (rotation) {
  5404. rotation.x = 0;
  5405. rotation.y = 0;
  5406. rotation.z = 0;
  5407. rotation.w = 1;
  5408. }
  5409. return false;
  5410. }
  5411. if (rotation) {
  5412. 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]);
  5413. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5414. }
  5415. return true;
  5416. };
  5417. /**
  5418. * Gets specific row of the matrix
  5419. * @param index defines the number of the row to get
  5420. * @returns the index-th row of the current matrix as a new Vector4
  5421. */
  5422. Matrix.prototype.getRow = function (index) {
  5423. if (index < 0 || index > 3) {
  5424. return null;
  5425. }
  5426. var i = index * 4;
  5427. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5428. };
  5429. /**
  5430. * Sets the index-th row of the current matrix to the vector4 values
  5431. * @param index defines the number of the row to set
  5432. * @param row defines the target vector4
  5433. * @returns the updated current matrix
  5434. */
  5435. Matrix.prototype.setRow = function (index, row) {
  5436. if (index < 0 || index > 3) {
  5437. return this;
  5438. }
  5439. var i = index * 4;
  5440. this.m[i + 0] = row.x;
  5441. this.m[i + 1] = row.y;
  5442. this.m[i + 2] = row.z;
  5443. this.m[i + 3] = row.w;
  5444. this._markAsUpdated();
  5445. return this;
  5446. };
  5447. /**
  5448. * Compute the transpose of the matrix
  5449. * @returns the new transposed matrix
  5450. */
  5451. Matrix.prototype.transpose = function () {
  5452. return Matrix.Transpose(this);
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix and store it in a given matrix
  5456. * @param result defines the target matrix
  5457. * @returns the current matrix
  5458. */
  5459. Matrix.prototype.transposeToRef = function (result) {
  5460. Matrix.TransposeToRef(this, result);
  5461. return this;
  5462. };
  5463. /**
  5464. * Sets the index-th row of the current matrix with the given 4 x float values
  5465. * @param index defines the row index
  5466. * @param x defines the x component to set
  5467. * @param y defines the y component to set
  5468. * @param z defines the z component to set
  5469. * @param w defines the w component to set
  5470. * @returns the updated current matrix
  5471. */
  5472. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5473. if (index < 0 || index > 3) {
  5474. return this;
  5475. }
  5476. var i = index * 4;
  5477. this.m[i + 0] = x;
  5478. this.m[i + 1] = y;
  5479. this.m[i + 2] = z;
  5480. this.m[i + 3] = w;
  5481. this._markAsUpdated();
  5482. return this;
  5483. };
  5484. /**
  5485. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5486. * @param scale defines the scale factor
  5487. * @returns a new matrix
  5488. */
  5489. Matrix.prototype.scale = function (scale) {
  5490. var result = new Matrix();
  5491. this.scaleToRef(scale, result);
  5492. return result;
  5493. };
  5494. /**
  5495. * Scale the current matrix values by a factor to a given result matrix
  5496. * @param scale defines the scale factor
  5497. * @param result defines the matrix to store the result
  5498. * @returns the current matrix
  5499. */
  5500. Matrix.prototype.scaleToRef = function (scale, result) {
  5501. for (var index = 0; index < 16; index++) {
  5502. result.m[index] = this.m[index] * scale;
  5503. }
  5504. result._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Scale the current matrix values by a factor and add the result to a given matrix
  5509. * @param scale defines the scale factor
  5510. * @param result defines the Matrix to store the result
  5511. * @returns the current matrix
  5512. */
  5513. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5514. for (var index = 0; index < 16; index++) {
  5515. result.m[index] += this.m[index] * scale;
  5516. }
  5517. result._markAsUpdated();
  5518. return this;
  5519. };
  5520. /**
  5521. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5522. * @param ref matrix to store the result
  5523. */
  5524. Matrix.prototype.toNormalMatrix = function (ref) {
  5525. this.invertToRef(ref);
  5526. ref.transpose();
  5527. var m = ref.m;
  5528. 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);
  5529. };
  5530. /**
  5531. * Gets only rotation part of the current matrix
  5532. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5533. */
  5534. Matrix.prototype.getRotationMatrix = function () {
  5535. var result = Matrix.Identity();
  5536. this.getRotationMatrixToRef(result);
  5537. return result;
  5538. };
  5539. /**
  5540. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5541. * @param result defines the target matrix to store data to
  5542. * @returns the current matrix
  5543. */
  5544. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5545. var m = this.m;
  5546. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5547. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5548. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5549. if (this.determinant() <= 0) {
  5550. sy *= -1;
  5551. }
  5552. if (sx === 0 || sy === 0 || sz === 0) {
  5553. Matrix.IdentityToRef(result);
  5554. }
  5555. else {
  5556. 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);
  5557. }
  5558. return this;
  5559. };
  5560. // Statics
  5561. /**
  5562. * Creates a matrix from an array
  5563. * @param array defines the source array
  5564. * @param offset defines an offset in the source array
  5565. * @returns a new Matrix set from the starting index of the given array
  5566. */
  5567. Matrix.FromArray = function (array, offset) {
  5568. var result = new Matrix();
  5569. if (!offset) {
  5570. offset = 0;
  5571. }
  5572. Matrix.FromArrayToRef(array, offset, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Copy the content of an array into a given matrix
  5577. * @param array defines the source array
  5578. * @param offset defines an offset in the source array
  5579. * @param result defines the target matrix
  5580. */
  5581. Matrix.FromArrayToRef = function (array, offset, result) {
  5582. for (var index = 0; index < 16; index++) {
  5583. result.m[index] = array[index + offset];
  5584. }
  5585. result._markAsUpdated();
  5586. };
  5587. /**
  5588. * Stores an array into a matrix after having multiplied each component by a given factor
  5589. * @param array defines the source array
  5590. * @param offset defines the offset in the source array
  5591. * @param scale defines the scaling factor
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5595. for (var index = 0; index < 16; index++) {
  5596. result.m[index] = array[index + offset] * scale;
  5597. }
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Stores a list of values (16) inside a given matrix
  5602. * @param initialM11 defines 1st value of 1st row
  5603. * @param initialM12 defines 2nd value of 1st row
  5604. * @param initialM13 defines 3rd value of 1st row
  5605. * @param initialM14 defines 4th value of 1st row
  5606. * @param initialM21 defines 1st value of 2nd row
  5607. * @param initialM22 defines 2nd value of 2nd row
  5608. * @param initialM23 defines 3rd value of 2nd row
  5609. * @param initialM24 defines 4th value of 2nd row
  5610. * @param initialM31 defines 1st value of 3rd row
  5611. * @param initialM32 defines 2nd value of 3rd row
  5612. * @param initialM33 defines 3rd value of 3rd row
  5613. * @param initialM34 defines 4th value of 3rd row
  5614. * @param initialM41 defines 1st value of 4th row
  5615. * @param initialM42 defines 2nd value of 4th row
  5616. * @param initialM43 defines 3rd value of 4th row
  5617. * @param initialM44 defines 4th value of 4th row
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5621. result.m[0] = initialM11;
  5622. result.m[1] = initialM12;
  5623. result.m[2] = initialM13;
  5624. result.m[3] = initialM14;
  5625. result.m[4] = initialM21;
  5626. result.m[5] = initialM22;
  5627. result.m[6] = initialM23;
  5628. result.m[7] = initialM24;
  5629. result.m[8] = initialM31;
  5630. result.m[9] = initialM32;
  5631. result.m[10] = initialM33;
  5632. result.m[11] = initialM34;
  5633. result.m[12] = initialM41;
  5634. result.m[13] = initialM42;
  5635. result.m[14] = initialM43;
  5636. result.m[15] = initialM44;
  5637. result._markAsUpdated();
  5638. };
  5639. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5640. /**
  5641. * Gets an identity matrix that must not be updated
  5642. */
  5643. get: function () {
  5644. return Matrix._identityReadOnly;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. /**
  5650. * Creates new matrix from a list of values (16)
  5651. * @param initialM11 defines 1st value of 1st row
  5652. * @param initialM12 defines 2nd value of 1st row
  5653. * @param initialM13 defines 3rd value of 1st row
  5654. * @param initialM14 defines 4th value of 1st row
  5655. * @param initialM21 defines 1st value of 2nd row
  5656. * @param initialM22 defines 2nd value of 2nd row
  5657. * @param initialM23 defines 3rd value of 2nd row
  5658. * @param initialM24 defines 4th value of 2nd row
  5659. * @param initialM31 defines 1st value of 3rd row
  5660. * @param initialM32 defines 2nd value of 3rd row
  5661. * @param initialM33 defines 3rd value of 3rd row
  5662. * @param initialM34 defines 4th value of 3rd row
  5663. * @param initialM41 defines 1st value of 4th row
  5664. * @param initialM42 defines 2nd value of 4th row
  5665. * @param initialM43 defines 3rd value of 4th row
  5666. * @param initialM44 defines 4th value of 4th row
  5667. * @returns the new matrix
  5668. */
  5669. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5670. var result = new Matrix();
  5671. result.m[0] = initialM11;
  5672. result.m[1] = initialM12;
  5673. result.m[2] = initialM13;
  5674. result.m[3] = initialM14;
  5675. result.m[4] = initialM21;
  5676. result.m[5] = initialM22;
  5677. result.m[6] = initialM23;
  5678. result.m[7] = initialM24;
  5679. result.m[8] = initialM31;
  5680. result.m[9] = initialM32;
  5681. result.m[10] = initialM33;
  5682. result.m[11] = initialM34;
  5683. result.m[12] = initialM41;
  5684. result.m[13] = initialM42;
  5685. result.m[14] = initialM43;
  5686. result.m[15] = initialM44;
  5687. return result;
  5688. };
  5689. /**
  5690. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5691. * @param scale defines the scale vector3
  5692. * @param rotation defines the rotation quaternion
  5693. * @param translation defines the translation vector3
  5694. * @returns a new matrix
  5695. */
  5696. Matrix.Compose = function (scale, rotation, translation) {
  5697. var result = Matrix.Identity();
  5698. Matrix.ComposeToRef(scale, rotation, translation, result);
  5699. return result;
  5700. };
  5701. /**
  5702. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @param result defines the target matrix
  5707. */
  5708. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5709. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5710. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5711. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5712. result.setTranslation(translation);
  5713. };
  5714. /**
  5715. * Creates a new identity matrix
  5716. * @returns a new identity matrix
  5717. */
  5718. Matrix.Identity = function () {
  5719. 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);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix and stores the result in a given matrix
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.IdentityToRef = function (result) {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new zero matrix
  5730. * @returns a new zero matrix
  5731. */
  5732. Matrix.Zero = function () {
  5733. 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);
  5734. };
  5735. /**
  5736. * Creates a new rotation matrix for "angle" radians around the X axis
  5737. * @param angle defines the angle (in radians) to use
  5738. * @return the new matrix
  5739. */
  5740. Matrix.RotationX = function (angle) {
  5741. var result = new Matrix();
  5742. Matrix.RotationXToRef(angle, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Creates a new matrix as the invert of a given matrix
  5747. * @param source defines the source matrix
  5748. * @returns the new matrix
  5749. */
  5750. Matrix.Invert = function (source) {
  5751. var result = new Matrix();
  5752. source.invertToRef(result);
  5753. return result;
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5757. * @param angle defines the angle (in radians) to use
  5758. * @param result defines the target matrix
  5759. */
  5760. Matrix.RotationXToRef = function (angle, result) {
  5761. var s = Math.sin(angle);
  5762. var c = Math.cos(angle);
  5763. result.m[0] = 1.0;
  5764. result.m[15] = 1.0;
  5765. result.m[5] = c;
  5766. result.m[10] = c;
  5767. result.m[9] = -s;
  5768. result.m[6] = s;
  5769. result.m[1] = 0.0;
  5770. result.m[2] = 0.0;
  5771. result.m[3] = 0.0;
  5772. result.m[4] = 0.0;
  5773. result.m[7] = 0.0;
  5774. result.m[8] = 0.0;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = 0.0;
  5777. result.m[13] = 0.0;
  5778. result.m[14] = 0.0;
  5779. result._markAsUpdated();
  5780. };
  5781. /**
  5782. * Creates a new rotation matrix for "angle" radians around the Y axis
  5783. * @param angle defines the angle (in radians) to use
  5784. * @return the new matrix
  5785. */
  5786. Matrix.RotationY = function (angle) {
  5787. var result = new Matrix();
  5788. Matrix.RotationYToRef(angle, result);
  5789. return result;
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5793. * @param angle defines the angle (in radians) to use
  5794. * @param result defines the target matrix
  5795. */
  5796. Matrix.RotationYToRef = function (angle, result) {
  5797. var s = Math.sin(angle);
  5798. var c = Math.cos(angle);
  5799. result.m[5] = 1.0;
  5800. result.m[15] = 1.0;
  5801. result.m[0] = c;
  5802. result.m[2] = -s;
  5803. result.m[8] = s;
  5804. result.m[10] = c;
  5805. result.m[1] = 0.0;
  5806. result.m[3] = 0.0;
  5807. result.m[4] = 0.0;
  5808. result.m[6] = 0.0;
  5809. result.m[7] = 0.0;
  5810. result.m[9] = 0.0;
  5811. result.m[11] = 0.0;
  5812. result.m[12] = 0.0;
  5813. result.m[13] = 0.0;
  5814. result.m[14] = 0.0;
  5815. result._markAsUpdated();
  5816. };
  5817. /**
  5818. * Creates a new rotation matrix for "angle" radians around the Z axis
  5819. * @param angle defines the angle (in radians) to use
  5820. * @return the new matrix
  5821. */
  5822. Matrix.RotationZ = function (angle) {
  5823. var result = new Matrix();
  5824. Matrix.RotationZToRef(angle, result);
  5825. return result;
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5829. * @param angle defines the angle (in radians) to use
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.RotationZToRef = function (angle, result) {
  5833. var s = Math.sin(angle);
  5834. var c = Math.cos(angle);
  5835. result.m[10] = 1.0;
  5836. result.m[15] = 1.0;
  5837. result.m[0] = c;
  5838. result.m[1] = s;
  5839. result.m[4] = -s;
  5840. result.m[5] = c;
  5841. result.m[2] = 0.0;
  5842. result.m[3] = 0.0;
  5843. result.m[6] = 0.0;
  5844. result.m[7] = 0.0;
  5845. result.m[8] = 0.0;
  5846. result.m[9] = 0.0;
  5847. result.m[11] = 0.0;
  5848. result.m[12] = 0.0;
  5849. result.m[13] = 0.0;
  5850. result.m[14] = 0.0;
  5851. result._markAsUpdated();
  5852. };
  5853. /**
  5854. * Creates a new rotation matrix for "angle" radians around the given axis
  5855. * @param axis defines the axis to use
  5856. * @param angle defines the angle (in radians) to use
  5857. * @return the new matrix
  5858. */
  5859. Matrix.RotationAxis = function (axis, angle) {
  5860. var result = Matrix.Zero();
  5861. Matrix.RotationAxisToRef(axis, angle, result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5866. * @param axis defines the axis to use
  5867. * @param angle defines the angle (in radians) to use
  5868. * @param result defines the target matrix
  5869. */
  5870. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5871. var s = Math.sin(-angle);
  5872. var c = Math.cos(-angle);
  5873. var c1 = 1 - c;
  5874. axis.normalize();
  5875. result.m[0] = (axis.x * axis.x) * c1 + c;
  5876. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5877. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5878. result.m[3] = 0.0;
  5879. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5880. result.m[5] = (axis.y * axis.y) * c1 + c;
  5881. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5882. result.m[7] = 0.0;
  5883. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5884. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5885. result.m[10] = (axis.z * axis.z) * c1 + c;
  5886. result.m[11] = 0.0;
  5887. result.m[15] = 1.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a rotation matrix
  5892. * @param yaw defines the yaw angle in radians (Y axis)
  5893. * @param pitch defines the pitch angle in radians (X axis)
  5894. * @param roll defines the roll angle in radians (X axis)
  5895. * @returns the new rotation matrix
  5896. */
  5897. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5898. var result = new Matrix();
  5899. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5900. return result;
  5901. };
  5902. /**
  5903. * Creates a rotation matrix and stores it in a given matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5910. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5911. this._tempQuaternion.toRotationMatrix(result);
  5912. };
  5913. /**
  5914. * Creates a scaling matrix
  5915. * @param x defines the scale factor on X axis
  5916. * @param y defines the scale factor on Y axis
  5917. * @param z defines the scale factor on Z axis
  5918. * @returns the new matrix
  5919. */
  5920. Matrix.Scaling = function (x, y, z) {
  5921. var result = Matrix.Zero();
  5922. Matrix.ScalingToRef(x, y, z, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a scaling matrix and stores it in a given matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.ScalingToRef = function (x, y, z, result) {
  5933. result.m[0] = x;
  5934. result.m[1] = 0.0;
  5935. result.m[2] = 0.0;
  5936. result.m[3] = 0.0;
  5937. result.m[4] = 0.0;
  5938. result.m[5] = y;
  5939. result.m[6] = 0.0;
  5940. result.m[7] = 0.0;
  5941. result.m[8] = 0.0;
  5942. result.m[9] = 0.0;
  5943. result.m[10] = z;
  5944. result.m[11] = 0.0;
  5945. result.m[12] = 0.0;
  5946. result.m[13] = 0.0;
  5947. result.m[14] = 0.0;
  5948. result.m[15] = 1.0;
  5949. result._markAsUpdated();
  5950. };
  5951. /**
  5952. * Creates a translation matrix
  5953. * @param x defines the translation on X axis
  5954. * @param y defines the translation on Y axis
  5955. * @param z defines the translationon Z axis
  5956. * @returns the new matrix
  5957. */
  5958. Matrix.Translation = function (x, y, z) {
  5959. var result = Matrix.Identity();
  5960. Matrix.TranslationToRef(x, y, z, result);
  5961. return result;
  5962. };
  5963. /**
  5964. * Creates a translation matrix and stores it in a given matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @param result defines the target matrix
  5969. */
  5970. Matrix.TranslationToRef = function (x, y, z, result) {
  5971. 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);
  5972. };
  5973. /**
  5974. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5975. * @param startValue defines the start value
  5976. * @param endValue defines the end value
  5977. * @param gradient defines the gradient factor
  5978. * @returns the new matrix
  5979. */
  5980. Matrix.Lerp = function (startValue, endValue, gradient) {
  5981. var result = Matrix.Zero();
  5982. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @param result defines the Matrix object where to store data
  5991. */
  5992. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5993. for (var index = 0; index < 16; index++) {
  5994. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5995. }
  5996. result._markAsUpdated();
  5997. };
  5998. /**
  5999. * Builds a new matrix whose values are computed by:
  6000. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6001. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6002. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6003. * @param startValue defines the first matrix
  6004. * @param endValue defines the second matrix
  6005. * @param gradient defines the gradient between the two matrices
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6009. var result = Matrix.Zero();
  6010. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6011. return result;
  6012. };
  6013. /**
  6014. * Update a matrix to values which are computed by:
  6015. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6016. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6017. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6018. * @param startValue defines the first matrix
  6019. * @param endValue defines the second matrix
  6020. * @param gradient defines the gradient between the two matrices
  6021. * @param result defines the target matrix
  6022. */
  6023. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6024. var startScale = MathTmp.Vector3[0];
  6025. var startRotation = MathTmp.Quaternion[0];
  6026. var startTranslation = MathTmp.Vector3[1];
  6027. startValue.decompose(startScale, startRotation, startTranslation);
  6028. var endScale = MathTmp.Vector3[2];
  6029. var endRotation = MathTmp.Quaternion[1];
  6030. var endTranslation = MathTmp.Vector3[3];
  6031. endValue.decompose(endScale, endRotation, endTranslation);
  6032. var resultScale = MathTmp.Vector3[4];
  6033. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6034. var resultRotation = MathTmp.Quaternion[2];
  6035. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6036. var resultTranslation = MathTmp.Vector3[5];
  6037. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6038. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6039. };
  6040. /**
  6041. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6042. * This function works in left handed mode
  6043. * @param eye defines the final position of the entity
  6044. * @param target defines where the entity should look at
  6045. * @param up defines the up vector for the entity
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.LookAtLH = function (eye, target, up) {
  6049. var result = Matrix.Zero();
  6050. Matrix.LookAtLHToRef(eye, target, up, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6055. * This function works in left handed mode
  6056. * @param eye defines the final position of the entity
  6057. * @param target defines where the entity should look at
  6058. * @param up defines the up vector for the entity
  6059. * @param result defines the target matrix
  6060. */
  6061. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6062. // Z axis
  6063. target.subtractToRef(eye, this._zAxis);
  6064. this._zAxis.normalize();
  6065. // X axis
  6066. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6067. if (this._xAxis.lengthSquared() === 0) {
  6068. this._xAxis.x = 1.0;
  6069. }
  6070. else {
  6071. this._xAxis.normalize();
  6072. }
  6073. // Y axis
  6074. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6075. this._yAxis.normalize();
  6076. // Eye angles
  6077. var ex = -Vector3.Dot(this._xAxis, eye);
  6078. var ey = -Vector3.Dot(this._yAxis, eye);
  6079. var ez = -Vector3.Dot(this._zAxis, eye);
  6080. 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);
  6081. };
  6082. /**
  6083. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6084. * This function works in right handed mode
  6085. * @param eye defines the final position of the entity
  6086. * @param target defines where the entity should look at
  6087. * @param up defines the up vector for the entity
  6088. * @returns the new matrix
  6089. */
  6090. Matrix.LookAtRH = function (eye, target, up) {
  6091. var result = Matrix.Zero();
  6092. Matrix.LookAtRHToRef(eye, target, up, result);
  6093. return result;
  6094. };
  6095. /**
  6096. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6097. * This function works in right handed mode
  6098. * @param eye defines the final position of the entity
  6099. * @param target defines where the entity should look at
  6100. * @param up defines the up vector for the entity
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6104. // Z axis
  6105. eye.subtractToRef(target, this._zAxis);
  6106. this._zAxis.normalize();
  6107. // X axis
  6108. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6109. if (this._xAxis.lengthSquared() === 0) {
  6110. this._xAxis.x = 1.0;
  6111. }
  6112. else {
  6113. this._xAxis.normalize();
  6114. }
  6115. // Y axis
  6116. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6117. this._yAxis.normalize();
  6118. // Eye angles
  6119. var ex = -Vector3.Dot(this._xAxis, eye);
  6120. var ey = -Vector3.Dot(this._yAxis, eye);
  6121. var ez = -Vector3.Dot(this._zAxis, eye);
  6122. 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);
  6123. };
  6124. /**
  6125. * Create a left-handed orthographic projection matrix
  6126. * @param width defines the viewport width
  6127. * @param height defines the viewport height
  6128. * @param znear defines the near clip plane
  6129. * @param zfar defines the far clip plane
  6130. * @returns a new matrix as a left-handed orthographic projection matrix
  6131. */
  6132. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6133. var matrix = Matrix.Zero();
  6134. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6135. return matrix;
  6136. };
  6137. /**
  6138. * Store a left-handed orthographic projection to a given matrix
  6139. * @param width defines the viewport width
  6140. * @param height defines the viewport height
  6141. * @param znear defines the near clip plane
  6142. * @param zfar defines the far clip plane
  6143. * @param result defines the target matrix
  6144. */
  6145. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6146. var n = znear;
  6147. var f = zfar;
  6148. var a = 2.0 / width;
  6149. var b = 2.0 / height;
  6150. var c = 2.0 / (f - n);
  6151. var d = -(f + n) / (f - n);
  6152. 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);
  6153. };
  6154. /**
  6155. * Create a left-handed orthographic projection matrix
  6156. * @param left defines the viewport left coordinate
  6157. * @param right defines the viewport right coordinate
  6158. * @param bottom defines the viewport bottom coordinate
  6159. * @param top defines the viewport top coordinate
  6160. * @param znear defines the near clip plane
  6161. * @param zfar defines the far clip plane
  6162. * @returns a new matrix as a left-handed orthographic projection matrix
  6163. */
  6164. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6165. var matrix = Matrix.Zero();
  6166. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6167. return matrix;
  6168. };
  6169. /**
  6170. * Stores a left-handed orthographic projection into a given matrix
  6171. * @param left defines the viewport left coordinate
  6172. * @param right defines the viewport right coordinate
  6173. * @param bottom defines the viewport bottom coordinate
  6174. * @param top defines the viewport top coordinate
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6180. var n = znear;
  6181. var f = zfar;
  6182. var a = 2.0 / (right - left);
  6183. var b = 2.0 / (top - bottom);
  6184. var c = 2.0 / (f - n);
  6185. var d = -(f + n) / (f - n);
  6186. var i0 = (left + right) / (left - right);
  6187. var i1 = (top + bottom) / (bottom - top);
  6188. 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);
  6189. };
  6190. /**
  6191. * Creates a right-handed orthographic projection matrix
  6192. * @param left defines the viewport left coordinate
  6193. * @param right defines the viewport right coordinate
  6194. * @param bottom defines the viewport bottom coordinate
  6195. * @param top defines the viewport top coordinate
  6196. * @param znear defines the near clip plane
  6197. * @param zfar defines the far clip plane
  6198. * @returns a new matrix as a right-handed orthographic projection matrix
  6199. */
  6200. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6201. var matrix = Matrix.Zero();
  6202. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6203. return matrix;
  6204. };
  6205. /**
  6206. * Stores a right-handed orthographic projection into a given matrix
  6207. * @param left defines the viewport left coordinate
  6208. * @param right defines the viewport right coordinate
  6209. * @param bottom defines the viewport bottom coordinate
  6210. * @param top defines the viewport top coordinate
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @param result defines the target matrix
  6214. */
  6215. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6216. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6217. result.m[10] *= -1.0;
  6218. };
  6219. /**
  6220. * Creates a left-handed perspective projection matrix
  6221. * @param width defines the viewport width
  6222. * @param height defines the viewport height
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a left-handed perspective projection matrix
  6226. */
  6227. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 * n / width;
  6232. var b = 2.0 * n / height;
  6233. var c = (f + n) / (f - n);
  6234. var d = -2.0 * f * n / (f - n);
  6235. 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);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Creates a left-handed perspective projection matrix
  6240. * @param fov defines the horizontal field of view
  6241. * @param aspect defines the aspect ratio
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @returns a new matrix as a left-handed perspective projection matrix
  6245. */
  6246. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6247. var matrix = Matrix.Zero();
  6248. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6249. return matrix;
  6250. };
  6251. /**
  6252. * Stores a left-handed perspective projection into a given matrix
  6253. * @param fov defines the horizontal field of view
  6254. * @param aspect defines the aspect ratio
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6259. */
  6260. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6261. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6262. var n = znear;
  6263. var f = zfar;
  6264. var t = 1.0 / (Math.tan(fov * 0.5));
  6265. var a = isVerticalFovFixed ? (t / aspect) : t;
  6266. var b = isVerticalFovFixed ? t : (t * aspect);
  6267. var c = (f + n) / (f - n);
  6268. var d = -2.0 * f * n / (f - n);
  6269. 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);
  6270. };
  6271. /**
  6272. * Creates a right-handed perspective projection matrix
  6273. * @param fov defines the horizontal field of view
  6274. * @param aspect defines the aspect ratio
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @returns a new matrix as a right-handed perspective projection matrix
  6278. */
  6279. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6280. var matrix = Matrix.Zero();
  6281. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6282. return matrix;
  6283. };
  6284. /**
  6285. * Stores a right-handed perspective projection into a given matrix
  6286. * @param fov defines the horizontal field of view
  6287. * @param aspect defines the aspect ratio
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6292. */
  6293. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6294. //alternatively this could be expressed as:
  6295. // m = PerspectiveFovLHToRef
  6296. // m[10] *= -1.0;
  6297. // m[11] *= -1.0;
  6298. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6299. var n = znear;
  6300. var f = zfar;
  6301. var t = 1.0 / (Math.tan(fov * 0.5));
  6302. var a = isVerticalFovFixed ? (t / aspect) : t;
  6303. var b = isVerticalFovFixed ? t : (t * aspect);
  6304. var c = -(f + n) / (f - n);
  6305. var d = -2 * f * n / (f - n);
  6306. 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);
  6307. };
  6308. /**
  6309. * Stores a perspective projection for WebVR info a given matrix
  6310. * @param fov defines the field of view
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6315. */
  6316. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6317. if (rightHanded === void 0) { rightHanded = false; }
  6318. var rightHandedFactor = rightHanded ? -1 : 1;
  6319. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6320. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6321. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6322. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6323. var xScale = 2.0 / (leftTan + rightTan);
  6324. var yScale = 2.0 / (upTan + downTan);
  6325. result.m[0] = xScale;
  6326. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6327. result.m[5] = yScale;
  6328. result.m[6] = result.m[7] = 0.0;
  6329. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6330. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6331. result.m[10] = -zfar / (znear - zfar);
  6332. result.m[11] = 1.0 * rightHandedFactor;
  6333. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6334. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Computes a complete transformation matrix
  6339. * @param viewport defines the viewport to use
  6340. * @param world defines the world matrix
  6341. * @param view defines the view matrix
  6342. * @param projection defines the projection matrix
  6343. * @param zmin defines the near clip plane
  6344. * @param zmax defines the far clip plane
  6345. * @returns the transformation matrix
  6346. */
  6347. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6348. var cw = viewport.width;
  6349. var ch = viewport.height;
  6350. var cx = viewport.x;
  6351. var cy = viewport.y;
  6352. 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);
  6353. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6354. };
  6355. /**
  6356. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6357. * @param matrix defines the matrix to use
  6358. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6359. */
  6360. Matrix.GetAsMatrix2x2 = function (matrix) {
  6361. return new Float32Array([
  6362. matrix.m[0], matrix.m[1],
  6363. matrix.m[4], matrix.m[5]
  6364. ]);
  6365. };
  6366. /**
  6367. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6368. * @param matrix defines the matrix to use
  6369. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6370. */
  6371. Matrix.GetAsMatrix3x3 = function (matrix) {
  6372. return new Float32Array([
  6373. matrix.m[0], matrix.m[1], matrix.m[2],
  6374. matrix.m[4], matrix.m[5], matrix.m[6],
  6375. matrix.m[8], matrix.m[9], matrix.m[10]
  6376. ]);
  6377. };
  6378. /**
  6379. * Compute the transpose of a given matrix
  6380. * @param matrix defines the matrix to transpose
  6381. * @returns the new matrix
  6382. */
  6383. Matrix.Transpose = function (matrix) {
  6384. var result = new Matrix();
  6385. Matrix.TransposeToRef(matrix, result);
  6386. return result;
  6387. };
  6388. /**
  6389. * Compute the transpose of a matrix and store it in a target matrix
  6390. * @param matrix defines the matrix to transpose
  6391. * @param result defines the target matrix
  6392. */
  6393. Matrix.TransposeToRef = function (matrix, result) {
  6394. result.m[0] = matrix.m[0];
  6395. result.m[1] = matrix.m[4];
  6396. result.m[2] = matrix.m[8];
  6397. result.m[3] = matrix.m[12];
  6398. result.m[4] = matrix.m[1];
  6399. result.m[5] = matrix.m[5];
  6400. result.m[6] = matrix.m[9];
  6401. result.m[7] = matrix.m[13];
  6402. result.m[8] = matrix.m[2];
  6403. result.m[9] = matrix.m[6];
  6404. result.m[10] = matrix.m[10];
  6405. result.m[11] = matrix.m[14];
  6406. result.m[12] = matrix.m[3];
  6407. result.m[13] = matrix.m[7];
  6408. result.m[14] = matrix.m[11];
  6409. result.m[15] = matrix.m[15];
  6410. };
  6411. /**
  6412. * Computes a reflection matrix from a plane
  6413. * @param plane defines the reflection plane
  6414. * @returns a new matrix
  6415. */
  6416. Matrix.Reflection = function (plane) {
  6417. var matrix = new Matrix();
  6418. Matrix.ReflectionToRef(plane, matrix);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Computes a reflection matrix from a plane
  6423. * @param plane defines the reflection plane
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.ReflectionToRef = function (plane, result) {
  6427. plane.normalize();
  6428. var x = plane.normal.x;
  6429. var y = plane.normal.y;
  6430. var z = plane.normal.z;
  6431. var temp = -2 * x;
  6432. var temp2 = -2 * y;
  6433. var temp3 = -2 * z;
  6434. result.m[0] = (temp * x) + 1;
  6435. result.m[1] = temp2 * x;
  6436. result.m[2] = temp3 * x;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = temp * y;
  6439. result.m[5] = (temp2 * y) + 1;
  6440. result.m[6] = temp3 * y;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = temp * z;
  6443. result.m[9] = temp2 * z;
  6444. result.m[10] = (temp3 * z) + 1;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = temp * plane.d;
  6447. result.m[13] = temp2 * plane.d;
  6448. result.m[14] = temp3 * plane.d;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6454. * @param xaxis defines the value of the 1st axis
  6455. * @param yaxis defines the value of the 2nd axis
  6456. * @param zaxis defines the value of the 3rd axis
  6457. * @param result defines the target matrix
  6458. */
  6459. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6460. result.m[0] = xaxis.x;
  6461. result.m[1] = xaxis.y;
  6462. result.m[2] = xaxis.z;
  6463. result.m[3] = 0.0;
  6464. result.m[4] = yaxis.x;
  6465. result.m[5] = yaxis.y;
  6466. result.m[6] = yaxis.z;
  6467. result.m[7] = 0.0;
  6468. result.m[8] = zaxis.x;
  6469. result.m[9] = zaxis.y;
  6470. result.m[10] = zaxis.z;
  6471. result.m[11] = 0.0;
  6472. result.m[12] = 0.0;
  6473. result.m[13] = 0.0;
  6474. result.m[14] = 0.0;
  6475. result.m[15] = 1.0;
  6476. result._markAsUpdated();
  6477. };
  6478. /**
  6479. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6480. * @param quat defines the quaternion to use
  6481. * @param result defines the target matrix
  6482. */
  6483. Matrix.FromQuaternionToRef = function (quat, result) {
  6484. var xx = quat.x * quat.x;
  6485. var yy = quat.y * quat.y;
  6486. var zz = quat.z * quat.z;
  6487. var xy = quat.x * quat.y;
  6488. var zw = quat.z * quat.w;
  6489. var zx = quat.z * quat.x;
  6490. var yw = quat.y * quat.w;
  6491. var yz = quat.y * quat.z;
  6492. var xw = quat.x * quat.w;
  6493. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6494. result.m[1] = 2.0 * (xy + zw);
  6495. result.m[2] = 2.0 * (zx - yw);
  6496. result.m[3] = 0.0;
  6497. result.m[4] = 2.0 * (xy - zw);
  6498. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6499. result.m[6] = 2.0 * (yz + xw);
  6500. result.m[7] = 0.0;
  6501. result.m[8] = 2.0 * (zx + yw);
  6502. result.m[9] = 2.0 * (yz - xw);
  6503. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6504. result.m[11] = 0.0;
  6505. result.m[12] = 0.0;
  6506. result.m[13] = 0.0;
  6507. result.m[14] = 0.0;
  6508. result.m[15] = 1.0;
  6509. result._markAsUpdated();
  6510. };
  6511. Matrix._tempQuaternion = new Quaternion();
  6512. Matrix._xAxis = Vector3.Zero();
  6513. Matrix._yAxis = Vector3.Zero();
  6514. Matrix._zAxis = Vector3.Zero();
  6515. Matrix._updateFlagSeed = 0;
  6516. Matrix._identityReadOnly = Matrix.Identity();
  6517. return Matrix;
  6518. }());
  6519. BABYLON.Matrix = Matrix;
  6520. var Plane = /** @class */ (function () {
  6521. /**
  6522. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6523. */
  6524. function Plane(a, b, c, d) {
  6525. this.normal = new Vector3(a, b, c);
  6526. this.d = d;
  6527. }
  6528. /**
  6529. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6530. */
  6531. Plane.prototype.asArray = function () {
  6532. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6533. };
  6534. // Methods
  6535. /**
  6536. * Returns a new plane copied from the current Plane.
  6537. */
  6538. Plane.prototype.clone = function () {
  6539. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6540. };
  6541. /**
  6542. * Returns the string "Plane".
  6543. */
  6544. Plane.prototype.getClassName = function () {
  6545. return "Plane";
  6546. };
  6547. /**
  6548. * Returns the Plane hash code.
  6549. */
  6550. Plane.prototype.getHashCode = function () {
  6551. var hash = this.normal.getHashCode();
  6552. hash = (hash * 397) ^ (this.d || 0);
  6553. return hash;
  6554. };
  6555. /**
  6556. * Normalize the current Plane in place.
  6557. * Returns the updated Plane.
  6558. */
  6559. Plane.prototype.normalize = function () {
  6560. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6561. var magnitude = 0.0;
  6562. if (norm !== 0) {
  6563. magnitude = 1.0 / norm;
  6564. }
  6565. this.normal.x *= magnitude;
  6566. this.normal.y *= magnitude;
  6567. this.normal.z *= magnitude;
  6568. this.d *= magnitude;
  6569. return this;
  6570. };
  6571. /**
  6572. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6573. */
  6574. Plane.prototype.transform = function (transformation) {
  6575. var transposedMatrix = Matrix.Transpose(transformation);
  6576. var x = this.normal.x;
  6577. var y = this.normal.y;
  6578. var z = this.normal.z;
  6579. var d = this.d;
  6580. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6581. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6582. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6583. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6584. return new Plane(normalX, normalY, normalZ, finalD);
  6585. };
  6586. /**
  6587. * Returns the dot product (float) of the point coordinates and the plane normal.
  6588. */
  6589. Plane.prototype.dotCoordinate = function (point) {
  6590. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6591. };
  6592. /**
  6593. * Updates the current Plane from the plane defined by the three given points.
  6594. * Returns the updated Plane.
  6595. */
  6596. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6597. var x1 = point2.x - point1.x;
  6598. var y1 = point2.y - point1.y;
  6599. var z1 = point2.z - point1.z;
  6600. var x2 = point3.x - point1.x;
  6601. var y2 = point3.y - point1.y;
  6602. var z2 = point3.z - point1.z;
  6603. var yz = (y1 * z2) - (z1 * y2);
  6604. var xz = (z1 * x2) - (x1 * z2);
  6605. var xy = (x1 * y2) - (y1 * x2);
  6606. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6607. var invPyth;
  6608. if (pyth !== 0) {
  6609. invPyth = 1.0 / pyth;
  6610. }
  6611. else {
  6612. invPyth = 0.0;
  6613. }
  6614. this.normal.x = yz * invPyth;
  6615. this.normal.y = xz * invPyth;
  6616. this.normal.z = xy * invPyth;
  6617. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6618. return this;
  6619. };
  6620. /**
  6621. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6622. */
  6623. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6624. var dot = Vector3.Dot(this.normal, direction);
  6625. return (dot <= epsilon);
  6626. };
  6627. /**
  6628. * Returns the signed distance (float) from the given point to the Plane.
  6629. */
  6630. Plane.prototype.signedDistanceTo = function (point) {
  6631. return Vector3.Dot(point, this.normal) + this.d;
  6632. };
  6633. // Statics
  6634. /**
  6635. * Returns a new Plane from the given array.
  6636. */
  6637. Plane.FromArray = function (array) {
  6638. return new Plane(array[0], array[1], array[2], array[3]);
  6639. };
  6640. /**
  6641. * Returns a new Plane defined by the three given points.
  6642. */
  6643. Plane.FromPoints = function (point1, point2, point3) {
  6644. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6645. result.copyFromPoints(point1, point2, point3);
  6646. return result;
  6647. };
  6648. /**
  6649. * Returns a new Plane the normal vector to this plane at the given origin point.
  6650. * Note : the vector "normal" is updated because normalized.
  6651. */
  6652. Plane.FromPositionAndNormal = function (origin, normal) {
  6653. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6654. normal.normalize();
  6655. result.normal = normal;
  6656. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6657. return result;
  6658. };
  6659. /**
  6660. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6661. */
  6662. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6663. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return Vector3.Dot(point, normal) + d;
  6665. };
  6666. return Plane;
  6667. }());
  6668. BABYLON.Plane = Plane;
  6669. var Viewport = /** @class */ (function () {
  6670. /**
  6671. * Creates a Viewport object located at (x, y) and sized (width, height).
  6672. */
  6673. function Viewport(x, y, width, height) {
  6674. this.x = x;
  6675. this.y = y;
  6676. this.width = width;
  6677. this.height = height;
  6678. }
  6679. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6680. if (renderWidthOrEngine.getRenderWidth) {
  6681. var engine = renderWidthOrEngine;
  6682. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6683. }
  6684. var renderWidth = renderWidthOrEngine;
  6685. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6686. };
  6687. /**
  6688. * Returns a new Viewport copied from the current one.
  6689. */
  6690. Viewport.prototype.clone = function () {
  6691. return new Viewport(this.x, this.y, this.width, this.height);
  6692. };
  6693. return Viewport;
  6694. }());
  6695. BABYLON.Viewport = Viewport;
  6696. var Frustum = /** @class */ (function () {
  6697. function Frustum() {
  6698. }
  6699. /**
  6700. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6701. */
  6702. Frustum.GetPlanes = function (transform) {
  6703. var frustumPlanes = [];
  6704. for (var index = 0; index < 6; index++) {
  6705. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6706. }
  6707. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6708. return frustumPlanes;
  6709. };
  6710. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6711. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6712. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6713. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6714. frustumPlane.d = transform.m[15] + transform.m[14];
  6715. frustumPlane.normalize();
  6716. };
  6717. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6719. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6720. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6721. frustumPlane.d = transform.m[15] - transform.m[14];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6726. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6727. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6728. frustumPlane.d = transform.m[15] + transform.m[12];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6732. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6733. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6734. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6735. frustumPlane.d = transform.m[15] - transform.m[12];
  6736. frustumPlane.normalize();
  6737. };
  6738. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6742. frustumPlane.d = transform.m[15] - transform.m[13];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6746. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6747. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6748. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6749. frustumPlane.d = transform.m[15] + transform.m[13];
  6750. frustumPlane.normalize();
  6751. };
  6752. /**
  6753. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6754. */
  6755. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6756. // Near
  6757. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6758. // Far
  6759. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6760. // Left
  6761. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6762. // Right
  6763. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6764. // Top
  6765. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6766. // Bottom
  6767. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6768. };
  6769. return Frustum;
  6770. }());
  6771. BABYLON.Frustum = Frustum;
  6772. /** Defines supported spaces */
  6773. var Space;
  6774. (function (Space) {
  6775. /** Local (object) space */
  6776. Space[Space["LOCAL"] = 0] = "LOCAL";
  6777. /** World space */
  6778. Space[Space["WORLD"] = 1] = "WORLD";
  6779. /** Bone space */
  6780. Space[Space["BONE"] = 2] = "BONE";
  6781. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6782. /** Defines the 3 main axes */
  6783. var Axis = /** @class */ (function () {
  6784. function Axis() {
  6785. }
  6786. /** X axis */
  6787. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6788. /** Y axis */
  6789. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6790. /** Z axis */
  6791. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6792. return Axis;
  6793. }());
  6794. BABYLON.Axis = Axis;
  6795. ;
  6796. var BezierCurve = /** @class */ (function () {
  6797. function BezierCurve() {
  6798. }
  6799. /**
  6800. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6801. */
  6802. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6803. // Extract X (which is equal to time here)
  6804. var f0 = 1 - 3 * x2 + 3 * x1;
  6805. var f1 = 3 * x2 - 6 * x1;
  6806. var f2 = 3 * x1;
  6807. var refinedT = t;
  6808. for (var i = 0; i < 5; i++) {
  6809. var refinedT2 = refinedT * refinedT;
  6810. var refinedT3 = refinedT2 * refinedT;
  6811. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6812. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6813. refinedT -= (x - t) * slope;
  6814. refinedT = Math.min(1, Math.max(0, refinedT));
  6815. }
  6816. // Resolve cubic bezier for the given x
  6817. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6818. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6819. Math.pow(refinedT, 3);
  6820. };
  6821. return BezierCurve;
  6822. }());
  6823. BABYLON.BezierCurve = BezierCurve;
  6824. /**
  6825. * Defines potential orientation for back face culling
  6826. */
  6827. var Orientation;
  6828. (function (Orientation) {
  6829. /**
  6830. * Clockwise
  6831. */
  6832. Orientation[Orientation["CW"] = 0] = "CW";
  6833. /** Counter clockwise */
  6834. Orientation[Orientation["CCW"] = 1] = "CCW";
  6835. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6836. /**
  6837. * Defines angle representation
  6838. */
  6839. var Angle = /** @class */ (function () {
  6840. /**
  6841. * Creates an Angle object of "radians" radians (float).
  6842. */
  6843. function Angle(radians) {
  6844. this._radians = radians;
  6845. if (this._radians < 0.0)
  6846. this._radians += (2.0 * Math.PI);
  6847. }
  6848. /**
  6849. * Get value in degrees
  6850. * @returns the Angle value in degrees (float)
  6851. */
  6852. Angle.prototype.degrees = function () {
  6853. return this._radians * 180.0 / Math.PI;
  6854. };
  6855. /**
  6856. * Get value in radians
  6857. * @returns the Angle value in radians (float)
  6858. */
  6859. Angle.prototype.radians = function () {
  6860. return this._radians;
  6861. };
  6862. /**
  6863. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6864. * @param a defines first vector
  6865. * @param b defines second vector
  6866. * @returns a new Angle
  6867. */
  6868. Angle.BetweenTwoPoints = function (a, b) {
  6869. var delta = b.subtract(a);
  6870. var theta = Math.atan2(delta.y, delta.x);
  6871. return new Angle(theta);
  6872. };
  6873. /**
  6874. * Gets a new Angle object from the given float in radians
  6875. * @param radians defines the angle value in radians
  6876. * @returns a new Angle
  6877. */
  6878. Angle.FromRadians = function (radians) {
  6879. return new Angle(radians);
  6880. };
  6881. /**
  6882. * Gets a new Angle object from the given float in degrees
  6883. * @param degrees defines the angle value in degrees
  6884. * @returns a new Angle
  6885. */
  6886. Angle.FromDegrees = function (degrees) {
  6887. return new Angle(degrees * Math.PI / 180.0);
  6888. };
  6889. return Angle;
  6890. }());
  6891. BABYLON.Angle = Angle;
  6892. var Arc2 = /** @class */ (function () {
  6893. /**
  6894. * Creates an Arc object from the three given points : start, middle and end.
  6895. */
  6896. function Arc2(startPoint, midPoint, endPoint) {
  6897. this.startPoint = startPoint;
  6898. this.midPoint = midPoint;
  6899. this.endPoint = endPoint;
  6900. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6901. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6902. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6903. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6904. 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);
  6905. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6906. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6907. var a1 = this.startAngle.degrees();
  6908. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6909. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6910. // angles correction
  6911. if (a2 - a1 > +180.0)
  6912. a2 -= 360.0;
  6913. if (a2 - a1 < -180.0)
  6914. a2 += 360.0;
  6915. if (a3 - a2 > +180.0)
  6916. a3 -= 360.0;
  6917. if (a3 - a2 < -180.0)
  6918. a3 += 360.0;
  6919. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6920. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6921. }
  6922. return Arc2;
  6923. }());
  6924. BABYLON.Arc2 = Arc2;
  6925. var Path2 = /** @class */ (function () {
  6926. /**
  6927. * Creates a Path2 object from the starting 2D coordinates x and y.
  6928. */
  6929. function Path2(x, y) {
  6930. this._points = new Array();
  6931. this._length = 0.0;
  6932. this.closed = false;
  6933. this._points.push(new Vector2(x, y));
  6934. }
  6935. /**
  6936. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6937. * Returns the updated Path2.
  6938. */
  6939. Path2.prototype.addLineTo = function (x, y) {
  6940. if (this.closed) {
  6941. return this;
  6942. }
  6943. var newPoint = new Vector2(x, y);
  6944. var previousPoint = this._points[this._points.length - 1];
  6945. this._points.push(newPoint);
  6946. this._length += newPoint.subtract(previousPoint).length();
  6947. return this;
  6948. };
  6949. /**
  6950. * 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.
  6951. * Returns the updated Path2.
  6952. */
  6953. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6954. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6955. if (this.closed) {
  6956. return this;
  6957. }
  6958. var startPoint = this._points[this._points.length - 1];
  6959. var midPoint = new Vector2(midX, midY);
  6960. var endPoint = new Vector2(endX, endY);
  6961. var arc = new Arc2(startPoint, midPoint, endPoint);
  6962. var increment = arc.angle.radians() / numberOfSegments;
  6963. if (arc.orientation === Orientation.CW)
  6964. increment *= -1;
  6965. var currentAngle = arc.startAngle.radians() + increment;
  6966. for (var i = 0; i < numberOfSegments; i++) {
  6967. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6968. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6969. this.addLineTo(x, y);
  6970. currentAngle += increment;
  6971. }
  6972. return this;
  6973. };
  6974. /**
  6975. * Closes the Path2.
  6976. * Returns the Path2.
  6977. */
  6978. Path2.prototype.close = function () {
  6979. this.closed = true;
  6980. return this;
  6981. };
  6982. /**
  6983. * Returns the Path2 total length (float).
  6984. */
  6985. Path2.prototype.length = function () {
  6986. var result = this._length;
  6987. if (!this.closed) {
  6988. var lastPoint = this._points[this._points.length - 1];
  6989. var firstPoint = this._points[0];
  6990. result += (firstPoint.subtract(lastPoint).length());
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns the Path2 internal array of points.
  6996. */
  6997. Path2.prototype.getPoints = function () {
  6998. return this._points;
  6999. };
  7000. /**
  7001. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7002. */
  7003. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7004. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7005. return Vector2.Zero();
  7006. }
  7007. var lengthPosition = normalizedLengthPosition * this.length();
  7008. var previousOffset = 0;
  7009. for (var i = 0; i < this._points.length; i++) {
  7010. var j = (i + 1) % this._points.length;
  7011. var a = this._points[i];
  7012. var b = this._points[j];
  7013. var bToA = b.subtract(a);
  7014. var nextOffset = (bToA.length() + previousOffset);
  7015. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7016. var dir = bToA.normalize();
  7017. var localOffset = lengthPosition - previousOffset;
  7018. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7019. }
  7020. previousOffset = nextOffset;
  7021. }
  7022. return Vector2.Zero();
  7023. };
  7024. /**
  7025. * Returns a new Path2 starting at the coordinates (x, y).
  7026. */
  7027. Path2.StartingAt = function (x, y) {
  7028. return new Path2(x, y);
  7029. };
  7030. return Path2;
  7031. }());
  7032. BABYLON.Path2 = Path2;
  7033. var Path3D = /** @class */ (function () {
  7034. /**
  7035. * new Path3D(path, normal, raw)
  7036. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7037. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7038. * path : an array of Vector3, the curve axis of the Path3D
  7039. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7040. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7041. */
  7042. function Path3D(path, firstNormal, raw) {
  7043. if (firstNormal === void 0) { firstNormal = null; }
  7044. this.path = path;
  7045. this._curve = new Array();
  7046. this._distances = new Array();
  7047. this._tangents = new Array();
  7048. this._normals = new Array();
  7049. this._binormals = new Array();
  7050. for (var p = 0; p < path.length; p++) {
  7051. this._curve[p] = path[p].clone(); // hard copy
  7052. }
  7053. this._raw = raw || false;
  7054. this._compute(firstNormal);
  7055. }
  7056. /**
  7057. * Returns the Path3D array of successive Vector3 designing its curve.
  7058. */
  7059. Path3D.prototype.getCurve = function () {
  7060. return this._curve;
  7061. };
  7062. /**
  7063. * Returns an array populated with tangent vectors on each Path3D curve point.
  7064. */
  7065. Path3D.prototype.getTangents = function () {
  7066. return this._tangents;
  7067. };
  7068. /**
  7069. * Returns an array populated with normal vectors on each Path3D curve point.
  7070. */
  7071. Path3D.prototype.getNormals = function () {
  7072. return this._normals;
  7073. };
  7074. /**
  7075. * Returns an array populated with binormal vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getBinormals = function () {
  7078. return this._binormals;
  7079. };
  7080. /**
  7081. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7082. */
  7083. Path3D.prototype.getDistances = function () {
  7084. return this._distances;
  7085. };
  7086. /**
  7087. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7088. * Returns the same object updated.
  7089. */
  7090. Path3D.prototype.update = function (path, firstNormal) {
  7091. if (firstNormal === void 0) { firstNormal = null; }
  7092. for (var p = 0; p < path.length; p++) {
  7093. this._curve[p].x = path[p].x;
  7094. this._curve[p].y = path[p].y;
  7095. this._curve[p].z = path[p].z;
  7096. }
  7097. this._compute(firstNormal);
  7098. return this;
  7099. };
  7100. // private function compute() : computes tangents, normals and binormals
  7101. Path3D.prototype._compute = function (firstNormal) {
  7102. var l = this._curve.length;
  7103. // first and last tangents
  7104. this._tangents[0] = this._getFirstNonNullVector(0);
  7105. if (!this._raw) {
  7106. this._tangents[0].normalize();
  7107. }
  7108. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7109. if (!this._raw) {
  7110. this._tangents[l - 1].normalize();
  7111. }
  7112. // normals and binormals at first point : arbitrary vector with _normalVector()
  7113. var tg0 = this._tangents[0];
  7114. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7115. this._normals[0] = pp0;
  7116. if (!this._raw) {
  7117. this._normals[0].normalize();
  7118. }
  7119. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7120. if (!this._raw) {
  7121. this._binormals[0].normalize();
  7122. }
  7123. this._distances[0] = 0.0;
  7124. // normals and binormals : next points
  7125. var prev; // previous vector (segment)
  7126. var cur; // current vector (segment)
  7127. var curTang; // current tangent
  7128. // previous normal
  7129. var prevBinor; // previous binormal
  7130. for (var i = 1; i < l; i++) {
  7131. // tangents
  7132. prev = this._getLastNonNullVector(i);
  7133. if (i < l - 1) {
  7134. cur = this._getFirstNonNullVector(i);
  7135. this._tangents[i] = prev.add(cur);
  7136. this._tangents[i].normalize();
  7137. }
  7138. this._distances[i] = this._distances[i - 1] + prev.length();
  7139. // normals and binormals
  7140. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7141. curTang = this._tangents[i];
  7142. prevBinor = this._binormals[i - 1];
  7143. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7144. if (!this._raw) {
  7145. this._normals[i].normalize();
  7146. }
  7147. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7148. if (!this._raw) {
  7149. this._binormals[i].normalize();
  7150. }
  7151. }
  7152. };
  7153. // private function getFirstNonNullVector(index)
  7154. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7155. Path3D.prototype._getFirstNonNullVector = function (index) {
  7156. var i = 1;
  7157. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7158. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7159. i++;
  7160. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7161. }
  7162. return nNVector;
  7163. };
  7164. // private function getLastNonNullVector(index)
  7165. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7166. Path3D.prototype._getLastNonNullVector = function (index) {
  7167. var i = 1;
  7168. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7169. while (nLVector.length() === 0 && index > i + 1) {
  7170. i++;
  7171. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7172. }
  7173. return nLVector;
  7174. };
  7175. // private function normalVector(v0, vt, va) :
  7176. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7177. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7178. Path3D.prototype._normalVector = function (v0, vt, va) {
  7179. var normal0;
  7180. var tgl = vt.length();
  7181. if (tgl === 0.0) {
  7182. tgl = 1.0;
  7183. }
  7184. if (va === undefined || va === null) {
  7185. var point;
  7186. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7187. point = new Vector3(0.0, -1.0, 0.0);
  7188. }
  7189. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7190. point = new Vector3(1.0, 0.0, 0.0);
  7191. }
  7192. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7193. point = new Vector3(0.0, 0.0, 1.0);
  7194. }
  7195. else {
  7196. point = Vector3.Zero();
  7197. }
  7198. normal0 = Vector3.Cross(vt, point);
  7199. }
  7200. else {
  7201. normal0 = Vector3.Cross(vt, va);
  7202. Vector3.CrossToRef(normal0, vt, normal0);
  7203. }
  7204. normal0.normalize();
  7205. return normal0;
  7206. };
  7207. return Path3D;
  7208. }());
  7209. BABYLON.Path3D = Path3D;
  7210. var Curve3 = /** @class */ (function () {
  7211. /**
  7212. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7213. * A Curve3 is designed from a series of successive Vector3.
  7214. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7215. */
  7216. function Curve3(points) {
  7217. this._length = 0.0;
  7218. this._points = points;
  7219. this._length = this._computeLength(points);
  7220. }
  7221. /**
  7222. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7223. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7224. * @param v1 (Vector3) the control point
  7225. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7226. * @param nbPoints (integer) the wanted number of points in the curve
  7227. */
  7228. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7229. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7230. var bez = new Array();
  7231. var equation = function (t, val0, val1, val2) {
  7232. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7233. return res;
  7234. };
  7235. for (var i = 0; i <= nbPoints; i++) {
  7236. 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)));
  7237. }
  7238. return new Curve3(bez);
  7239. };
  7240. /**
  7241. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7242. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7243. * @param v1 (Vector3) the first control point
  7244. * @param v2 (Vector3) the second control point
  7245. * @param v3 (Vector3) the end point of the Cubic Bezier
  7246. * @param nbPoints (integer) the wanted number of points in the curve
  7247. */
  7248. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7249. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7250. var bez = new Array();
  7251. var equation = function (t, val0, val1, val2, val3) {
  7252. 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;
  7253. return res;
  7254. };
  7255. for (var i = 0; i <= nbPoints; i++) {
  7256. 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)));
  7257. }
  7258. return new Curve3(bez);
  7259. };
  7260. /**
  7261. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7262. * @param p1 (Vector3) the origin point of the Hermite Spline
  7263. * @param t1 (Vector3) the tangent vector at the origin point
  7264. * @param p2 (Vector3) the end point of the Hermite Spline
  7265. * @param t2 (Vector3) the tangent vector at the end point
  7266. * @param nbPoints (integer) the wanted number of points in the curve
  7267. */
  7268. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7269. var hermite = new Array();
  7270. var step = 1.0 / nbPoints;
  7271. for (var i = 0; i <= nbPoints; i++) {
  7272. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7273. }
  7274. return new Curve3(hermite);
  7275. };
  7276. /**
  7277. * Returns a Curve3 object along a CatmullRom Spline curve :
  7278. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7279. * @param nbPoints (integer) the wanted number of points between each curve control points
  7280. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7283. var catmullRom = new Array();
  7284. var step = 1.0 / nbPoints;
  7285. var amount = 0.0;
  7286. if (closed) {
  7287. var pointsCount = points.length;
  7288. for (var i = 0; i < pointsCount; i++) {
  7289. amount = 0;
  7290. for (var c = 0; c < nbPoints; c++) {
  7291. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7292. amount += step;
  7293. }
  7294. }
  7295. catmullRom.push(catmullRom[0]);
  7296. }
  7297. else {
  7298. var totalPoints = new Array();
  7299. totalPoints.push(points[0].clone());
  7300. Array.prototype.push.apply(totalPoints, points);
  7301. totalPoints.push(points[points.length - 1].clone());
  7302. for (var i = 0; i < totalPoints.length - 3; i++) {
  7303. amount = 0;
  7304. for (var c = 0; c < nbPoints; c++) {
  7305. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7306. amount += step;
  7307. }
  7308. }
  7309. i--;
  7310. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7311. }
  7312. return new Curve3(catmullRom);
  7313. };
  7314. /**
  7315. * Returns the Curve3 stored array of successive Vector3
  7316. */
  7317. Curve3.prototype.getPoints = function () {
  7318. return this._points;
  7319. };
  7320. /**
  7321. * Returns the computed length (float) of the curve.
  7322. */
  7323. Curve3.prototype.length = function () {
  7324. return this._length;
  7325. };
  7326. /**
  7327. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7328. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7329. * curveA and curveB keep unchanged.
  7330. */
  7331. Curve3.prototype.continue = function (curve) {
  7332. var lastPoint = this._points[this._points.length - 1];
  7333. var continuedPoints = this._points.slice();
  7334. var curvePoints = curve.getPoints();
  7335. for (var i = 1; i < curvePoints.length; i++) {
  7336. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7337. }
  7338. var continuedCurve = new Curve3(continuedPoints);
  7339. return continuedCurve;
  7340. };
  7341. Curve3.prototype._computeLength = function (path) {
  7342. var l = 0;
  7343. for (var i = 1; i < path.length; i++) {
  7344. l += (path[i].subtract(path[i - 1])).length();
  7345. }
  7346. return l;
  7347. };
  7348. return Curve3;
  7349. }());
  7350. BABYLON.Curve3 = Curve3;
  7351. // Vertex formats
  7352. var PositionNormalVertex = /** @class */ (function () {
  7353. function PositionNormalVertex(position, normal) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. this.position = position;
  7357. this.normal = normal;
  7358. }
  7359. PositionNormalVertex.prototype.clone = function () {
  7360. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7361. };
  7362. return PositionNormalVertex;
  7363. }());
  7364. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7365. var PositionNormalTextureVertex = /** @class */ (function () {
  7366. function PositionNormalTextureVertex(position, normal, uv) {
  7367. if (position === void 0) { position = Vector3.Zero(); }
  7368. if (normal === void 0) { normal = Vector3.Up(); }
  7369. if (uv === void 0) { uv = Vector2.Zero(); }
  7370. this.position = position;
  7371. this.normal = normal;
  7372. this.uv = uv;
  7373. }
  7374. PositionNormalTextureVertex.prototype.clone = function () {
  7375. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7376. };
  7377. return PositionNormalTextureVertex;
  7378. }());
  7379. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7380. // Temporary pre-allocated objects for engine internal use
  7381. // usage in any internal function :
  7382. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7383. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7384. var Tmp = /** @class */ (function () {
  7385. function Tmp() {
  7386. }
  7387. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7388. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7389. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7390. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7391. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7392. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7393. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7394. Matrix.Zero(), Matrix.Zero(),
  7395. Matrix.Zero(), Matrix.Zero(),
  7396. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7397. return Tmp;
  7398. }());
  7399. BABYLON.Tmp = Tmp;
  7400. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7401. var MathTmp = /** @class */ (function () {
  7402. function MathTmp() {
  7403. }
  7404. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7405. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7406. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7407. return MathTmp;
  7408. }());
  7409. })(BABYLON || (BABYLON = {}));
  7410. //# sourceMappingURL=babylon.math.js.map
  7411. var BABYLON;
  7412. (function (BABYLON) {
  7413. var Scalar = /** @class */ (function () {
  7414. function Scalar() {
  7415. }
  7416. /**
  7417. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7418. */
  7419. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7420. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7421. var num = a - b;
  7422. return -epsilon <= num && num <= epsilon;
  7423. };
  7424. /**
  7425. * Returns a string : the upper case translation of the number i to hexadecimal.
  7426. */
  7427. Scalar.ToHex = function (i) {
  7428. var str = i.toString(16);
  7429. if (i <= 15) {
  7430. return ("0" + str).toUpperCase();
  7431. }
  7432. return str.toUpperCase();
  7433. };
  7434. /**
  7435. * Returns -1 if value is negative and +1 is value is positive.
  7436. * Returns the value itself if it's equal to zero.
  7437. */
  7438. Scalar.Sign = function (value) {
  7439. value = +value; // convert to a number
  7440. if (value === 0 || isNaN(value))
  7441. return value;
  7442. return value > 0 ? 1 : -1;
  7443. };
  7444. /**
  7445. * Returns the value itself if it's between min and max.
  7446. * Returns min if the value is lower than min.
  7447. * Returns max if the value is greater than max.
  7448. */
  7449. Scalar.Clamp = function (value, min, max) {
  7450. if (min === void 0) { min = 0; }
  7451. if (max === void 0) { max = 1; }
  7452. return Math.min(max, Math.max(min, value));
  7453. };
  7454. /**
  7455. * Returns the log2 of value.
  7456. */
  7457. Scalar.Log2 = function (value) {
  7458. return Math.log(value) * Math.LOG2E;
  7459. };
  7460. /**
  7461. * Loops the value, so that it is never larger than length and never smaller than 0.
  7462. *
  7463. * This is similar to the modulo operator but it works with floating point numbers.
  7464. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7465. * With t = 5 and length = 2.5, the result would be 0.0.
  7466. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7467. */
  7468. Scalar.Repeat = function (value, length) {
  7469. return value - Math.floor(value / length) * length;
  7470. };
  7471. /**
  7472. * Normalize the value between 0.0 and 1.0 using min and max values
  7473. */
  7474. Scalar.Normalize = function (value, min, max) {
  7475. return (value - min) / (max - min);
  7476. };
  7477. /**
  7478. * Denormalize the value from 0.0 and 1.0 using min and max values
  7479. */
  7480. Scalar.Denormalize = function (normalized, min, max) {
  7481. return (normalized * (max - min) + min);
  7482. };
  7483. /**
  7484. * Calculates the shortest difference between two given angles given in degrees.
  7485. */
  7486. Scalar.DeltaAngle = function (current, target) {
  7487. var num = Scalar.Repeat(target - current, 360.0);
  7488. if (num > 180.0) {
  7489. num -= 360.0;
  7490. }
  7491. return num;
  7492. };
  7493. /**
  7494. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7495. *
  7496. * The returned value will move back and forth between 0 and length
  7497. */
  7498. Scalar.PingPong = function (tx, length) {
  7499. var t = Scalar.Repeat(tx, length * 2.0);
  7500. return length - Math.abs(t - length);
  7501. };
  7502. /**
  7503. * Interpolates between min and max with smoothing at the limits.
  7504. *
  7505. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7506. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7507. */
  7508. Scalar.SmoothStep = function (from, to, tx) {
  7509. var t = Scalar.Clamp(tx);
  7510. t = -2.0 * t * t * t + 3.0 * t * t;
  7511. return to * t + from * (1.0 - t);
  7512. };
  7513. /**
  7514. * Moves a value current towards target.
  7515. *
  7516. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7517. * Negative values of maxDelta pushes the value away from target.
  7518. */
  7519. Scalar.MoveTowards = function (current, target, maxDelta) {
  7520. var result = 0;
  7521. if (Math.abs(target - current) <= maxDelta) {
  7522. result = target;
  7523. }
  7524. else {
  7525. result = current + Scalar.Sign(target - current) * maxDelta;
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7531. *
  7532. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7533. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7534. */
  7535. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7536. var num = Scalar.DeltaAngle(current, target);
  7537. var result = 0;
  7538. if (-maxDelta < num && num < maxDelta) {
  7539. result = target;
  7540. }
  7541. else {
  7542. target = current + num;
  7543. result = Scalar.MoveTowards(current, target, maxDelta);
  7544. }
  7545. return result;
  7546. };
  7547. /**
  7548. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7549. */
  7550. Scalar.Lerp = function (start, end, amount) {
  7551. return start + ((end - start) * amount);
  7552. };
  7553. /**
  7554. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7555. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7556. */
  7557. Scalar.LerpAngle = function (start, end, amount) {
  7558. var num = Scalar.Repeat(end - start, 360.0);
  7559. if (num > 180.0) {
  7560. num -= 360.0;
  7561. }
  7562. return start + num * Scalar.Clamp(amount);
  7563. };
  7564. /**
  7565. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7566. */
  7567. Scalar.InverseLerp = function (a, b, value) {
  7568. var result = 0;
  7569. if (a != b) {
  7570. result = Scalar.Clamp((value - a) / (b - a));
  7571. }
  7572. else {
  7573. result = 0.0;
  7574. }
  7575. return result;
  7576. };
  7577. /**
  7578. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7579. */
  7580. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7581. var squared = amount * amount;
  7582. var cubed = amount * squared;
  7583. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7584. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7585. var part3 = (cubed - (2.0 * squared)) + amount;
  7586. var part4 = cubed - squared;
  7587. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7588. };
  7589. /**
  7590. * Returns a random float number between and min and max values
  7591. */
  7592. Scalar.RandomRange = function (min, max) {
  7593. if (min === max)
  7594. return min;
  7595. return ((Math.random() * (max - min)) + min);
  7596. };
  7597. /**
  7598. * This function returns percentage of a number in a given range.
  7599. *
  7600. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7601. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7602. */
  7603. Scalar.RangeToPercent = function (number, min, max) {
  7604. return ((number - min) / (max - min));
  7605. };
  7606. /**
  7607. * This function returns number that corresponds to the percentage in a given range.
  7608. *
  7609. * PercentToRange(0.34,0,100) will return 34.
  7610. */
  7611. Scalar.PercentToRange = function (percent, min, max) {
  7612. return ((max - min) * percent + min);
  7613. };
  7614. /**
  7615. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7616. * @param angle The angle to normalize in radian.
  7617. * @return The converted angle.
  7618. */
  7619. Scalar.NormalizeRadians = function (angle) {
  7620. // More precise but slower version kept for reference.
  7621. // angle = angle % Tools.TwoPi;
  7622. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7623. //if (angle > Math.PI) {
  7624. // angle -= Tools.TwoPi;
  7625. //}
  7626. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7627. return angle;
  7628. };
  7629. /**
  7630. * Two pi constants convenient for computation.
  7631. */
  7632. Scalar.TwoPi = Math.PI * 2;
  7633. return Scalar;
  7634. }());
  7635. BABYLON.Scalar = Scalar;
  7636. })(BABYLON || (BABYLON = {}));
  7637. //# sourceMappingURL=babylon.math.scalar.js.map
  7638. //# sourceMappingURL=babylon.mixins.js.map
  7639. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7640. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7641. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7642. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7643. //# sourceMappingURL=babylon.webgl2.js.map
  7644. var BABYLON;
  7645. (function (BABYLON) {
  7646. var __decoratorInitialStore = {};
  7647. var __mergedStore = {};
  7648. var _copySource = function (creationFunction, source, instanciate) {
  7649. var destination = creationFunction();
  7650. // Tags
  7651. if (BABYLON.Tags) {
  7652. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7653. }
  7654. var classStore = getMergedStore(destination);
  7655. // Properties
  7656. for (var property in classStore) {
  7657. var propertyDescriptor = classStore[property];
  7658. var sourceProperty = source[property];
  7659. var propertyType = propertyDescriptor.type;
  7660. if (sourceProperty !== undefined && sourceProperty !== null) {
  7661. switch (propertyType) {
  7662. case 0: // Value
  7663. case 6: // Mesh reference
  7664. case 11: // Camera reference
  7665. destination[property] = sourceProperty;
  7666. break;
  7667. case 1: // Texture
  7668. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7669. break;
  7670. case 2: // Color3
  7671. case 3: // FresnelParameters
  7672. case 4: // Vector2
  7673. case 5: // Vector3
  7674. case 7: // Color Curves
  7675. case 10: // Quaternion
  7676. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7677. break;
  7678. }
  7679. }
  7680. }
  7681. return destination;
  7682. };
  7683. function getDirectStore(target) {
  7684. var classKey = target.getClassName();
  7685. if (!__decoratorInitialStore[classKey]) {
  7686. __decoratorInitialStore[classKey] = {};
  7687. }
  7688. return __decoratorInitialStore[classKey];
  7689. }
  7690. /**
  7691. * Return the list of properties flagged as serializable
  7692. * @param target: host object
  7693. */
  7694. function getMergedStore(target) {
  7695. var classKey = target.getClassName();
  7696. if (__mergedStore[classKey]) {
  7697. return __mergedStore[classKey];
  7698. }
  7699. __mergedStore[classKey] = {};
  7700. var store = __mergedStore[classKey];
  7701. var currentTarget = target;
  7702. var currentKey = classKey;
  7703. while (currentKey) {
  7704. var initialStore = __decoratorInitialStore[currentKey];
  7705. for (var property in initialStore) {
  7706. store[property] = initialStore[property];
  7707. }
  7708. var parent_1 = void 0;
  7709. var done = false;
  7710. do {
  7711. parent_1 = Object.getPrototypeOf(currentTarget);
  7712. if (!parent_1.getClassName) {
  7713. done = true;
  7714. break;
  7715. }
  7716. if (parent_1.getClassName() !== currentKey) {
  7717. break;
  7718. }
  7719. currentTarget = parent_1;
  7720. } while (parent_1);
  7721. if (done) {
  7722. break;
  7723. }
  7724. currentKey = parent_1.getClassName();
  7725. currentTarget = parent_1;
  7726. }
  7727. return store;
  7728. }
  7729. function generateSerializableMember(type, sourceName) {
  7730. return function (target, propertyKey) {
  7731. var classStore = getDirectStore(target);
  7732. if (!classStore[propertyKey]) {
  7733. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7734. }
  7735. };
  7736. }
  7737. function generateExpandMember(setCallback, targetKey) {
  7738. if (targetKey === void 0) { targetKey = null; }
  7739. return function (target, propertyKey) {
  7740. var key = targetKey || ("_" + propertyKey);
  7741. Object.defineProperty(target, propertyKey, {
  7742. get: function () {
  7743. return this[key];
  7744. },
  7745. set: function (value) {
  7746. if (this[key] === value) {
  7747. return;
  7748. }
  7749. this[key] = value;
  7750. target[setCallback].apply(this);
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. };
  7756. }
  7757. function expandToProperty(callback, targetKey) {
  7758. if (targetKey === void 0) { targetKey = null; }
  7759. return generateExpandMember(callback, targetKey);
  7760. }
  7761. BABYLON.expandToProperty = expandToProperty;
  7762. function serialize(sourceName) {
  7763. return generateSerializableMember(0, sourceName); // value member
  7764. }
  7765. BABYLON.serialize = serialize;
  7766. function serializeAsTexture(sourceName) {
  7767. return generateSerializableMember(1, sourceName); // texture member
  7768. }
  7769. BABYLON.serializeAsTexture = serializeAsTexture;
  7770. function serializeAsColor3(sourceName) {
  7771. return generateSerializableMember(2, sourceName); // color3 member
  7772. }
  7773. BABYLON.serializeAsColor3 = serializeAsColor3;
  7774. function serializeAsFresnelParameters(sourceName) {
  7775. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7776. }
  7777. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7778. function serializeAsVector2(sourceName) {
  7779. return generateSerializableMember(4, sourceName); // vector2 member
  7780. }
  7781. BABYLON.serializeAsVector2 = serializeAsVector2;
  7782. function serializeAsVector3(sourceName) {
  7783. return generateSerializableMember(5, sourceName); // vector3 member
  7784. }
  7785. BABYLON.serializeAsVector3 = serializeAsVector3;
  7786. function serializeAsMeshReference(sourceName) {
  7787. return generateSerializableMember(6, sourceName); // mesh reference member
  7788. }
  7789. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7790. function serializeAsColorCurves(sourceName) {
  7791. return generateSerializableMember(7, sourceName); // color curves
  7792. }
  7793. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7794. function serializeAsColor4(sourceName) {
  7795. return generateSerializableMember(8, sourceName); // color 4
  7796. }
  7797. BABYLON.serializeAsColor4 = serializeAsColor4;
  7798. function serializeAsImageProcessingConfiguration(sourceName) {
  7799. return generateSerializableMember(9, sourceName); // image processing
  7800. }
  7801. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7802. function serializeAsQuaternion(sourceName) {
  7803. return generateSerializableMember(10, sourceName); // quaternion member
  7804. }
  7805. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7806. /**
  7807. * Decorator used to define property that can be serialized as reference to a camera
  7808. * @param sourceName defines the name of the property to decorate
  7809. */
  7810. function serializeAsCameraReference(sourceName) {
  7811. return generateSerializableMember(11, sourceName); // camera reference member
  7812. }
  7813. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7814. var SerializationHelper = /** @class */ (function () {
  7815. function SerializationHelper() {
  7816. }
  7817. SerializationHelper.Serialize = function (entity, serializationObject) {
  7818. if (!serializationObject) {
  7819. serializationObject = {};
  7820. }
  7821. // Tags
  7822. if (BABYLON.Tags) {
  7823. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7824. }
  7825. var serializedProperties = getMergedStore(entity);
  7826. // Properties
  7827. for (var property in serializedProperties) {
  7828. var propertyDescriptor = serializedProperties[property];
  7829. var targetPropertyName = propertyDescriptor.sourceName || property;
  7830. var propertyType = propertyDescriptor.type;
  7831. var sourceProperty = entity[property];
  7832. if (sourceProperty !== undefined && sourceProperty !== null) {
  7833. switch (propertyType) {
  7834. case 0: // Value
  7835. serializationObject[targetPropertyName] = sourceProperty;
  7836. break;
  7837. case 1: // Texture
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 2: // Color3
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 3: // FresnelParameters
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 4: // Vector2
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 5: // Vector3
  7850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7851. break;
  7852. case 6: // Mesh reference
  7853. serializationObject[targetPropertyName] = sourceProperty.id;
  7854. break;
  7855. case 7: // Color Curves
  7856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7857. break;
  7858. case 8: // Color 4
  7859. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7860. break;
  7861. case 9: // Image Processing
  7862. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7863. break;
  7864. case 10: // Quaternion
  7865. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7866. break;
  7867. case 11: // Camera reference
  7868. serializationObject[targetPropertyName] = sourceProperty.id;
  7869. break;
  7870. }
  7871. }
  7872. }
  7873. return serializationObject;
  7874. };
  7875. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7876. if (rootUrl === void 0) { rootUrl = null; }
  7877. var destination = creationFunction();
  7878. if (!rootUrl) {
  7879. rootUrl = "";
  7880. }
  7881. // Tags
  7882. if (BABYLON.Tags) {
  7883. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7884. }
  7885. var classStore = getMergedStore(destination);
  7886. // Properties
  7887. for (var property in classStore) {
  7888. var propertyDescriptor = classStore[property];
  7889. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7890. var propertyType = propertyDescriptor.type;
  7891. if (sourceProperty !== undefined && sourceProperty !== null) {
  7892. var dest = destination;
  7893. switch (propertyType) {
  7894. case 0: // Value
  7895. dest[property] = sourceProperty;
  7896. break;
  7897. case 1: // Texture
  7898. if (scene) {
  7899. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7900. }
  7901. break;
  7902. case 2: // Color3
  7903. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7904. break;
  7905. case 3: // FresnelParameters
  7906. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7907. break;
  7908. case 4: // Vector2
  7909. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7910. break;
  7911. case 5: // Vector3
  7912. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7913. break;
  7914. case 6: // Mesh reference
  7915. if (scene) {
  7916. dest[property] = scene.getLastMeshByID(sourceProperty);
  7917. }
  7918. break;
  7919. case 7: // Color Curves
  7920. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7921. break;
  7922. case 8: // Color 4
  7923. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7924. break;
  7925. case 9: // Image Processing
  7926. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7927. break;
  7928. case 10: // Quaternion
  7929. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7930. break;
  7931. case 11: // Camera reference
  7932. if (scene) {
  7933. dest[property] = scene.getCameraByID(sourceProperty);
  7934. }
  7935. break;
  7936. }
  7937. }
  7938. }
  7939. return destination;
  7940. };
  7941. SerializationHelper.Clone = function (creationFunction, source) {
  7942. return _copySource(creationFunction, source, false);
  7943. };
  7944. SerializationHelper.Instanciate = function (creationFunction, source) {
  7945. return _copySource(creationFunction, source, true);
  7946. };
  7947. return SerializationHelper;
  7948. }());
  7949. BABYLON.SerializationHelper = SerializationHelper;
  7950. })(BABYLON || (BABYLON = {}));
  7951. //# sourceMappingURL=babylon.decorators.js.map
  7952. var BABYLON;
  7953. (function (BABYLON) {
  7954. /**
  7955. * Wrapper class for promise with external resolve and reject.
  7956. */
  7957. var Deferred = /** @class */ (function () {
  7958. /**
  7959. * Constructor for this deferred object.
  7960. */
  7961. function Deferred() {
  7962. var _this = this;
  7963. this.promise = new Promise(function (resolve, reject) {
  7964. _this._resolve = resolve;
  7965. _this._reject = reject;
  7966. });
  7967. }
  7968. Object.defineProperty(Deferred.prototype, "resolve", {
  7969. /**
  7970. * The resolve method of the promise associated with this deferred object.
  7971. */
  7972. get: function () {
  7973. return this._resolve;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Deferred.prototype, "reject", {
  7979. /**
  7980. * The reject method of the promise associated with this deferred object.
  7981. */
  7982. get: function () {
  7983. return this._reject;
  7984. },
  7985. enumerable: true,
  7986. configurable: true
  7987. });
  7988. return Deferred;
  7989. }());
  7990. BABYLON.Deferred = Deferred;
  7991. })(BABYLON || (BABYLON = {}));
  7992. //# sourceMappingURL=babylon.deferred.js.map
  7993. var BABYLON;
  7994. (function (BABYLON) {
  7995. /**
  7996. * A class serves as a medium between the observable and its observers
  7997. */
  7998. var EventState = /** @class */ (function () {
  7999. /**
  8000. * Create a new EventState
  8001. * @param mask defines the mask associated with this state
  8002. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8003. * @param target defines the original target of the state
  8004. * @param currentTarget defines the current target of the state
  8005. */
  8006. function EventState(mask, skipNextObservers, target, currentTarget) {
  8007. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8008. this.initalize(mask, skipNextObservers, target, currentTarget);
  8009. }
  8010. /**
  8011. * Initialize the current event state
  8012. * @param mask defines the mask associated with this state
  8013. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8014. * @param target defines the original target of the state
  8015. * @param currentTarget defines the current target of the state
  8016. * @returns the current event state
  8017. */
  8018. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8019. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8020. this.mask = mask;
  8021. this.skipNextObservers = skipNextObservers;
  8022. this.target = target;
  8023. this.currentTarget = currentTarget;
  8024. return this;
  8025. };
  8026. return EventState;
  8027. }());
  8028. BABYLON.EventState = EventState;
  8029. /**
  8030. * Represent an Observer registered to a given Observable object.
  8031. */
  8032. var Observer = /** @class */ (function () {
  8033. /**
  8034. * Creates a new observer
  8035. * @param callback defines the callback to call when the observer is notified
  8036. * @param mask defines the mask of the observer (used to filter notifications)
  8037. * @param scope defines the current scope used to restore the JS context
  8038. */
  8039. function Observer(
  8040. /**
  8041. * Defines the callback to call when the observer is notified
  8042. */
  8043. callback,
  8044. /**
  8045. * Defines the mask of the observer (used to filter notifications)
  8046. */
  8047. mask,
  8048. /**
  8049. * Defines the current scope used to restore the JS context
  8050. */
  8051. scope) {
  8052. if (scope === void 0) { scope = null; }
  8053. this.callback = callback;
  8054. this.mask = mask;
  8055. this.scope = scope;
  8056. /** @hidden */
  8057. this._willBeUnregistered = false;
  8058. /**
  8059. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8060. */
  8061. this.unregisterOnNextCall = false;
  8062. }
  8063. return Observer;
  8064. }());
  8065. BABYLON.Observer = Observer;
  8066. /**
  8067. * Represent a list of observers registered to multiple Observables object.
  8068. */
  8069. var MultiObserver = /** @class */ (function () {
  8070. function MultiObserver() {
  8071. }
  8072. /**
  8073. * Release associated resources
  8074. */
  8075. MultiObserver.prototype.dispose = function () {
  8076. if (this._observers && this._observables) {
  8077. for (var index = 0; index < this._observers.length; index++) {
  8078. this._observables[index].remove(this._observers[index]);
  8079. }
  8080. }
  8081. this._observers = null;
  8082. this._observables = null;
  8083. };
  8084. /**
  8085. * Raise a callback when one of the observable will notify
  8086. * @param observables defines a list of observables to watch
  8087. * @param callback defines the callback to call on notification
  8088. * @param mask defines the mask used to filter notifications
  8089. * @param scope defines the current scope used to restore the JS context
  8090. * @returns the new MultiObserver
  8091. */
  8092. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8093. if (mask === void 0) { mask = -1; }
  8094. if (scope === void 0) { scope = null; }
  8095. var result = new MultiObserver();
  8096. result._observers = new Array();
  8097. result._observables = observables;
  8098. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8099. var observable = observables_1[_i];
  8100. var observer = observable.add(callback, mask, false, scope);
  8101. if (observer) {
  8102. result._observers.push(observer);
  8103. }
  8104. }
  8105. return result;
  8106. };
  8107. return MultiObserver;
  8108. }());
  8109. BABYLON.MultiObserver = MultiObserver;
  8110. /**
  8111. * The Observable class is a simple implementation of the Observable pattern.
  8112. *
  8113. * 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.
  8114. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8115. * 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).
  8116. * 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.
  8117. */
  8118. var Observable = /** @class */ (function () {
  8119. /**
  8120. * Creates a new observable
  8121. * @param onObserverAdded defines a callback to call when a new observer is added
  8122. */
  8123. function Observable(onObserverAdded) {
  8124. this._observers = new Array();
  8125. this._eventState = new EventState(0);
  8126. if (onObserverAdded) {
  8127. this._onObserverAdded = onObserverAdded;
  8128. }
  8129. }
  8130. /**
  8131. * Create a new Observer with the specified callback
  8132. * @param callback the callback that will be executed for that Observer
  8133. * @param mask the mask used to filter observers
  8134. * @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.
  8135. * @param scope optional scope for the callback to be called from
  8136. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8137. * @returns the new observer created for the callback
  8138. */
  8139. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8140. if (mask === void 0) { mask = -1; }
  8141. if (insertFirst === void 0) { insertFirst = false; }
  8142. if (scope === void 0) { scope = null; }
  8143. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8144. if (!callback) {
  8145. return null;
  8146. }
  8147. var observer = new Observer(callback, mask, scope);
  8148. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8149. if (insertFirst) {
  8150. this._observers.unshift(observer);
  8151. }
  8152. else {
  8153. this._observers.push(observer);
  8154. }
  8155. if (this._onObserverAdded) {
  8156. this._onObserverAdded(observer);
  8157. }
  8158. return observer;
  8159. };
  8160. /**
  8161. * Create a new Observer with the specified callback and unregisters after the next notification
  8162. * @param callback the callback that will be executed for that Observer
  8163. * @returns the new observer created for the callback
  8164. */
  8165. Observable.prototype.addOnce = function (callback) {
  8166. return this.add(callback, undefined, undefined, undefined, true);
  8167. };
  8168. /**
  8169. * Remove an Observer from the Observable object
  8170. * @param observer the instance of the Observer to remove
  8171. * @returns false if it doesn't belong to this Observable
  8172. */
  8173. Observable.prototype.remove = function (observer) {
  8174. if (!observer) {
  8175. return false;
  8176. }
  8177. var index = this._observers.indexOf(observer);
  8178. if (index !== -1) {
  8179. this._observers.splice(index, 1);
  8180. return true;
  8181. }
  8182. return false;
  8183. };
  8184. /**
  8185. * Remove a callback from the Observable object
  8186. * @param callback the callback to remove
  8187. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8188. * @returns false if it doesn't belong to this Observable
  8189. */
  8190. Observable.prototype.removeCallback = function (callback, scope) {
  8191. for (var index = 0; index < this._observers.length; index++) {
  8192. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8193. this._observers.splice(index, 1);
  8194. return true;
  8195. }
  8196. }
  8197. return false;
  8198. };
  8199. Observable.prototype._deferUnregister = function (observer) {
  8200. var _this = this;
  8201. observer.unregisterOnNextCall = false;
  8202. observer._willBeUnregistered = true;
  8203. BABYLON.Tools.SetImmediate(function () {
  8204. _this.remove(observer);
  8205. });
  8206. };
  8207. /**
  8208. * Notify all Observers by calling their respective callback with the given data
  8209. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8210. * @param eventData defines the data to send to all observers
  8211. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8215. */
  8216. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8217. if (mask === void 0) { mask = -1; }
  8218. if (!this._observers.length) {
  8219. return true;
  8220. }
  8221. var state = this._eventState;
  8222. state.mask = mask;
  8223. state.target = target;
  8224. state.currentTarget = currentTarget;
  8225. state.skipNextObservers = false;
  8226. state.lastReturnValue = eventData;
  8227. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8228. var obs = _a[_i];
  8229. if (obs._willBeUnregistered) {
  8230. continue;
  8231. }
  8232. if (obs.mask & mask) {
  8233. if (obs.scope) {
  8234. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8235. }
  8236. else {
  8237. state.lastReturnValue = obs.callback(eventData, state);
  8238. }
  8239. if (obs.unregisterOnNextCall) {
  8240. this._deferUnregister(obs);
  8241. }
  8242. }
  8243. if (state.skipNextObservers) {
  8244. return false;
  8245. }
  8246. }
  8247. return true;
  8248. };
  8249. /**
  8250. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8251. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8252. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8253. * and it is crucial that all callbacks will be executed.
  8254. * The order of the callbacks is kept, callbacks are not executed parallel.
  8255. *
  8256. * @param eventData The data to be sent to each callback
  8257. * @param mask is used to filter observers defaults to -1
  8258. * @param target defines the callback target (see EventState)
  8259. * @param currentTarget defines he current object in the bubbling phase
  8260. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8261. */
  8262. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8263. var _this = this;
  8264. if (mask === void 0) { mask = -1; }
  8265. // create an empty promise
  8266. var p = Promise.resolve(eventData);
  8267. // no observers? return this promise.
  8268. if (!this._observers.length) {
  8269. return p;
  8270. }
  8271. var state = this._eventState;
  8272. state.mask = mask;
  8273. state.target = target;
  8274. state.currentTarget = currentTarget;
  8275. state.skipNextObservers = false;
  8276. // execute one callback after another (not using Promise.all, the order is important)
  8277. this._observers.forEach(function (obs) {
  8278. if (state.skipNextObservers) {
  8279. return;
  8280. }
  8281. if (obs._willBeUnregistered) {
  8282. return;
  8283. }
  8284. if (obs.mask & mask) {
  8285. if (obs.scope) {
  8286. p = p.then(function (lastReturnedValue) {
  8287. state.lastReturnValue = lastReturnedValue;
  8288. return obs.callback.apply(obs.scope, [eventData, state]);
  8289. });
  8290. }
  8291. else {
  8292. p = p.then(function (lastReturnedValue) {
  8293. state.lastReturnValue = lastReturnedValue;
  8294. return obs.callback(eventData, state);
  8295. });
  8296. }
  8297. if (obs.unregisterOnNextCall) {
  8298. _this._deferUnregister(obs);
  8299. }
  8300. }
  8301. });
  8302. // return the eventData
  8303. return p.then(function () { return eventData; });
  8304. };
  8305. /**
  8306. * Notify a specific observer
  8307. * @param observer defines the observer to notify
  8308. * @param eventData defines the data to be sent to each callback
  8309. * @param mask is used to filter observers defaults to -1
  8310. */
  8311. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8312. if (mask === void 0) { mask = -1; }
  8313. var state = this._eventState;
  8314. state.mask = mask;
  8315. state.skipNextObservers = false;
  8316. observer.callback(eventData, state);
  8317. };
  8318. /**
  8319. * Gets a boolean indicating if the observable has at least one observer
  8320. * @returns true is the Observable has at least one Observer registered
  8321. */
  8322. Observable.prototype.hasObservers = function () {
  8323. return this._observers.length > 0;
  8324. };
  8325. /**
  8326. * Clear the list of observers
  8327. */
  8328. Observable.prototype.clear = function () {
  8329. this._observers = new Array();
  8330. this._onObserverAdded = null;
  8331. };
  8332. /**
  8333. * Clone the current observable
  8334. * @returns a new observable
  8335. */
  8336. Observable.prototype.clone = function () {
  8337. var result = new Observable();
  8338. result._observers = this._observers.slice(0);
  8339. return result;
  8340. };
  8341. /**
  8342. * Does this observable handles observer registered with a given mask
  8343. * @param mask defines the mask to be tested
  8344. * @return whether or not one observer registered with the given mask is handeled
  8345. **/
  8346. Observable.prototype.hasSpecificMask = function (mask) {
  8347. if (mask === void 0) { mask = -1; }
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs.mask & mask || obs.mask === mask) {
  8351. return true;
  8352. }
  8353. }
  8354. return false;
  8355. };
  8356. return Observable;
  8357. }());
  8358. BABYLON.Observable = Observable;
  8359. })(BABYLON || (BABYLON = {}));
  8360. //# sourceMappingURL=babylon.observable.js.map
  8361. var BABYLON;
  8362. (function (BABYLON) {
  8363. var SmartArray = /** @class */ (function () {
  8364. function SmartArray(capacity) {
  8365. this.length = 0;
  8366. this.data = new Array(capacity);
  8367. this._id = SmartArray._GlobalId++;
  8368. }
  8369. SmartArray.prototype.push = function (value) {
  8370. this.data[this.length++] = value;
  8371. if (this.length > this.data.length) {
  8372. this.data.length *= 2;
  8373. }
  8374. };
  8375. SmartArray.prototype.forEach = function (func) {
  8376. for (var index = 0; index < this.length; index++) {
  8377. func(this.data[index]);
  8378. }
  8379. };
  8380. SmartArray.prototype.sort = function (compareFn) {
  8381. this.data.sort(compareFn);
  8382. };
  8383. SmartArray.prototype.reset = function () {
  8384. this.length = 0;
  8385. };
  8386. SmartArray.prototype.dispose = function () {
  8387. this.reset();
  8388. if (this.data) {
  8389. this.data.length = 0;
  8390. this.data = [];
  8391. }
  8392. };
  8393. SmartArray.prototype.concat = function (array) {
  8394. if (array.length === 0) {
  8395. return;
  8396. }
  8397. if (this.length + array.length > this.data.length) {
  8398. this.data.length = (this.length + array.length) * 2;
  8399. }
  8400. for (var index = 0; index < array.length; index++) {
  8401. this.data[this.length++] = (array.data || array)[index];
  8402. }
  8403. };
  8404. SmartArray.prototype.indexOf = function (value) {
  8405. var position = this.data.indexOf(value);
  8406. if (position >= this.length) {
  8407. return -1;
  8408. }
  8409. return position;
  8410. };
  8411. SmartArray.prototype.contains = function (value) {
  8412. return this.data.indexOf(value) !== -1;
  8413. };
  8414. // Statics
  8415. SmartArray._GlobalId = 0;
  8416. return SmartArray;
  8417. }());
  8418. BABYLON.SmartArray = SmartArray;
  8419. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8420. __extends(SmartArrayNoDuplicate, _super);
  8421. function SmartArrayNoDuplicate() {
  8422. var _this = _super !== null && _super.apply(this, arguments) || this;
  8423. _this._duplicateId = 0;
  8424. return _this;
  8425. }
  8426. SmartArrayNoDuplicate.prototype.push = function (value) {
  8427. _super.prototype.push.call(this, value);
  8428. if (!value.__smartArrayFlags) {
  8429. value.__smartArrayFlags = {};
  8430. }
  8431. value.__smartArrayFlags[this._id] = this._duplicateId;
  8432. };
  8433. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8434. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8435. return false;
  8436. }
  8437. this.push(value);
  8438. return true;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.reset = function () {
  8441. _super.prototype.reset.call(this);
  8442. this._duplicateId++;
  8443. };
  8444. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8445. if (array.length === 0) {
  8446. return;
  8447. }
  8448. if (this.length + array.length > this.data.length) {
  8449. this.data.length = (this.length + array.length) * 2;
  8450. }
  8451. for (var index = 0; index < array.length; index++) {
  8452. var item = (array.data || array)[index];
  8453. this.pushNoDuplicate(item);
  8454. }
  8455. };
  8456. return SmartArrayNoDuplicate;
  8457. }(SmartArray));
  8458. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8459. })(BABYLON || (BABYLON = {}));
  8460. //# sourceMappingURL=babylon.smartArray.js.map
  8461. var BABYLON;
  8462. (function (BABYLON) {
  8463. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8464. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8465. var LoadFileError = /** @class */ (function (_super) {
  8466. __extends(LoadFileError, _super);
  8467. function LoadFileError(message, request) {
  8468. var _this = _super.call(this, message) || this;
  8469. _this.request = request;
  8470. _this.name = "LoadFileError";
  8471. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8472. return _this;
  8473. }
  8474. // Polyfill for Object.setPrototypeOf if necessary.
  8475. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8476. return LoadFileError;
  8477. }(Error));
  8478. BABYLON.LoadFileError = LoadFileError;
  8479. var RetryStrategy = /** @class */ (function () {
  8480. function RetryStrategy() {
  8481. }
  8482. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8483. if (maxRetries === void 0) { maxRetries = 3; }
  8484. if (baseInterval === void 0) { baseInterval = 500; }
  8485. return function (url, request, retryIndex) {
  8486. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8487. return -1;
  8488. }
  8489. return Math.pow(2, retryIndex) * baseInterval;
  8490. };
  8491. };
  8492. return RetryStrategy;
  8493. }());
  8494. BABYLON.RetryStrategy = RetryStrategy;
  8495. // Screenshots
  8496. var screenshotCanvas;
  8497. var cloneValue = function (source, destinationObject) {
  8498. if (!source)
  8499. return null;
  8500. if (source instanceof BABYLON.Mesh) {
  8501. return null;
  8502. }
  8503. if (source instanceof BABYLON.SubMesh) {
  8504. return source.clone(destinationObject);
  8505. }
  8506. else if (source.clone) {
  8507. return source.clone();
  8508. }
  8509. return null;
  8510. };
  8511. var Tools = /** @class */ (function () {
  8512. function Tools() {
  8513. }
  8514. /**
  8515. * Interpolates between a and b via alpha
  8516. * @param a The lower value (returned when alpha = 0)
  8517. * @param b The upper value (returned when alpha = 1)
  8518. * @param alpha The interpolation-factor
  8519. * @return The mixed value
  8520. */
  8521. Tools.Mix = function (a, b, alpha) {
  8522. return a * (1 - alpha) + b * alpha;
  8523. };
  8524. Tools.Instantiate = function (className) {
  8525. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8526. return Tools.RegisteredExternalClasses[className];
  8527. }
  8528. var arr = className.split(".");
  8529. var fn = (window || this);
  8530. for (var i = 0, len = arr.length; i < len; i++) {
  8531. fn = fn[arr[i]];
  8532. }
  8533. if (typeof fn !== "function") {
  8534. return null;
  8535. }
  8536. return fn;
  8537. };
  8538. /**
  8539. * Provides a slice function that will work even on IE
  8540. * @param data defines the array to slice
  8541. * @param start defines the start of the data (optional)
  8542. * @param end defines the end of the data (optional)
  8543. * @returns the new sliced array
  8544. */
  8545. Tools.Slice = function (data, start, end) {
  8546. if (data.slice) {
  8547. return data.slice(start, end);
  8548. }
  8549. return Array.prototype.slice.call(data, start, end);
  8550. };
  8551. Tools.SetImmediate = function (action) {
  8552. if (window.setImmediate) {
  8553. window.setImmediate(action);
  8554. }
  8555. else {
  8556. setTimeout(action, 1);
  8557. }
  8558. };
  8559. Tools.IsExponentOfTwo = function (value) {
  8560. var count = 1;
  8561. do {
  8562. count *= 2;
  8563. } while (count < value);
  8564. return count === value;
  8565. };
  8566. /**
  8567. * Returns the nearest 32-bit single precision float representation of a Number
  8568. * @param value A Number. If the parameter is of a different type, it will get converted
  8569. * to a number or to NaN if it cannot be converted
  8570. * @returns number
  8571. */
  8572. Tools.FloatRound = function (value) {
  8573. if (Math.fround) {
  8574. return Math.fround(value);
  8575. }
  8576. return (Tools._tmpFloatArray[0] = value);
  8577. };
  8578. /**
  8579. * Find the next highest power of two.
  8580. * @param x Number to start search from.
  8581. * @return Next highest power of two.
  8582. */
  8583. Tools.CeilingPOT = function (x) {
  8584. x--;
  8585. x |= x >> 1;
  8586. x |= x >> 2;
  8587. x |= x >> 4;
  8588. x |= x >> 8;
  8589. x |= x >> 16;
  8590. x++;
  8591. return x;
  8592. };
  8593. /**
  8594. * Find the next lowest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next lowest power of two.
  8597. */
  8598. Tools.FloorPOT = function (x) {
  8599. x = x | (x >> 1);
  8600. x = x | (x >> 2);
  8601. x = x | (x >> 4);
  8602. x = x | (x >> 8);
  8603. x = x | (x >> 16);
  8604. return x - (x >> 1);
  8605. };
  8606. /**
  8607. * Find the nearest power of two.
  8608. * @param x Number to start search from.
  8609. * @return Next nearest power of two.
  8610. */
  8611. Tools.NearestPOT = function (x) {
  8612. var c = Tools.CeilingPOT(x);
  8613. var f = Tools.FloorPOT(x);
  8614. return (c - x) > (x - f) ? f : c;
  8615. };
  8616. Tools.GetExponentOfTwo = function (value, max, mode) {
  8617. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8618. var pot;
  8619. switch (mode) {
  8620. case BABYLON.Engine.SCALEMODE_FLOOR:
  8621. pot = Tools.FloorPOT(value);
  8622. break;
  8623. case BABYLON.Engine.SCALEMODE_NEAREST:
  8624. pot = Tools.NearestPOT(value);
  8625. break;
  8626. case BABYLON.Engine.SCALEMODE_CEILING:
  8627. default:
  8628. pot = Tools.CeilingPOT(value);
  8629. break;
  8630. }
  8631. return Math.min(pot, max);
  8632. };
  8633. Tools.GetFilename = function (path) {
  8634. var index = path.lastIndexOf("/");
  8635. if (index < 0)
  8636. return path;
  8637. return path.substring(index + 1);
  8638. };
  8639. /**
  8640. * Extracts the "folder" part of a path (everything before the filename).
  8641. * @param uri The URI to extract the info from
  8642. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8643. * @returns The "folder" part of the path
  8644. */
  8645. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8646. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8647. var index = uri.lastIndexOf("/");
  8648. if (index < 0) {
  8649. if (returnUnchangedIfNoSlash) {
  8650. return uri;
  8651. }
  8652. return "";
  8653. }
  8654. return uri.substring(0, index + 1);
  8655. };
  8656. Tools.GetDOMTextContent = function (element) {
  8657. var result = "";
  8658. var child = element.firstChild;
  8659. while (child) {
  8660. if (child.nodeType === 3) {
  8661. result += child.textContent;
  8662. }
  8663. child = child.nextSibling;
  8664. }
  8665. return result;
  8666. };
  8667. Tools.ToDegrees = function (angle) {
  8668. return angle * 180 / Math.PI;
  8669. };
  8670. Tools.ToRadians = function (angle) {
  8671. return angle * Math.PI / 180;
  8672. };
  8673. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8674. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8675. var output = "";
  8676. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8677. var i = 0;
  8678. var bytes = new Uint8Array(buffer);
  8679. while (i < bytes.length) {
  8680. chr1 = bytes[i++];
  8681. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8682. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8683. enc1 = chr1 >> 2;
  8684. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8685. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8686. enc4 = chr3 & 63;
  8687. if (isNaN(chr2)) {
  8688. enc3 = enc4 = 64;
  8689. }
  8690. else if (isNaN(chr3)) {
  8691. enc4 = 64;
  8692. }
  8693. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8694. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8695. }
  8696. return "data:image/png;base64," + output;
  8697. };
  8698. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8699. if (bias === void 0) { bias = null; }
  8700. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8701. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8702. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8703. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8704. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8705. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8706. }
  8707. if (bias) {
  8708. minimum.x -= minimum.x * bias.x + bias.y;
  8709. minimum.y -= minimum.y * bias.x + bias.y;
  8710. minimum.z -= minimum.z * bias.x + bias.y;
  8711. maximum.x += maximum.x * bias.x + bias.y;
  8712. maximum.y += maximum.y * bias.x + bias.y;
  8713. maximum.z += maximum.z * bias.x + bias.y;
  8714. }
  8715. return {
  8716. minimum: minimum,
  8717. maximum: maximum
  8718. };
  8719. };
  8720. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8721. if (bias === void 0) { bias = null; }
  8722. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8723. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8724. if (!stride) {
  8725. stride = 3;
  8726. }
  8727. for (var index = start; index < start + count; index++) {
  8728. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8729. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8730. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8731. }
  8732. if (bias) {
  8733. minimum.x -= minimum.x * bias.x + bias.y;
  8734. minimum.y -= minimum.y * bias.x + bias.y;
  8735. minimum.z -= minimum.z * bias.x + bias.y;
  8736. maximum.x += maximum.x * bias.x + bias.y;
  8737. maximum.y += maximum.y * bias.x + bias.y;
  8738. maximum.z += maximum.z * bias.x + bias.y;
  8739. }
  8740. return {
  8741. minimum: minimum,
  8742. maximum: maximum
  8743. };
  8744. };
  8745. Tools.Vector2ArrayFeeder = function (array) {
  8746. return function (index) {
  8747. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8748. var length = isFloatArray ? array.length / 2 : array.length;
  8749. if (index >= length) {
  8750. return null;
  8751. }
  8752. if (isFloatArray) {
  8753. var fa = array;
  8754. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8755. }
  8756. var a = array;
  8757. return a[index];
  8758. };
  8759. };
  8760. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8761. if (bias === void 0) { bias = null; }
  8762. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8763. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8764. var i = 0;
  8765. var cur = feeder(i++);
  8766. while (cur) {
  8767. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8768. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8769. cur = feeder(i++);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. }
  8777. return {
  8778. minimum: minimum,
  8779. maximum: maximum
  8780. };
  8781. };
  8782. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8783. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8784. return null;
  8785. return Array.isArray(obj) ? obj : [obj];
  8786. };
  8787. // Misc.
  8788. Tools.GetPointerPrefix = function () {
  8789. var eventPrefix = "pointer";
  8790. // Check if pointer events are supported
  8791. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8792. eventPrefix = "mouse";
  8793. }
  8794. return eventPrefix;
  8795. };
  8796. /**
  8797. * @param func - the function to be called
  8798. * @param requester - the object that will request the next frame. Falls back to window.
  8799. */
  8800. Tools.QueueNewFrame = function (func, requester) {
  8801. if (!Tools.IsWindowObjectExist()) {
  8802. return setTimeout(func, 16);
  8803. }
  8804. if (!requester) {
  8805. requester = window;
  8806. }
  8807. if (requester.requestAnimationFrame) {
  8808. return requester.requestAnimationFrame(func);
  8809. }
  8810. else if (requester.msRequestAnimationFrame) {
  8811. return requester.msRequestAnimationFrame(func);
  8812. }
  8813. else if (requester.webkitRequestAnimationFrame) {
  8814. return requester.webkitRequestAnimationFrame(func);
  8815. }
  8816. else if (requester.mozRequestAnimationFrame) {
  8817. return requester.mozRequestAnimationFrame(func);
  8818. }
  8819. else if (requester.oRequestAnimationFrame) {
  8820. return requester.oRequestAnimationFrame(func);
  8821. }
  8822. else {
  8823. return window.setTimeout(func, 16);
  8824. }
  8825. };
  8826. Tools.RequestFullscreen = function (element) {
  8827. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8828. if (!requestFunction)
  8829. return;
  8830. requestFunction.call(element);
  8831. };
  8832. Tools.ExitFullscreen = function () {
  8833. if (document.exitFullscreen) {
  8834. document.exitFullscreen();
  8835. }
  8836. else if (document.mozCancelFullScreen) {
  8837. document.mozCancelFullScreen();
  8838. }
  8839. else if (document.webkitCancelFullScreen) {
  8840. document.webkitCancelFullScreen();
  8841. }
  8842. else if (document.msCancelFullScreen) {
  8843. document.msCancelFullScreen();
  8844. }
  8845. };
  8846. Tools.SetCorsBehavior = function (url, element) {
  8847. if (url && url.indexOf("data:") === 0) {
  8848. return;
  8849. }
  8850. if (Tools.CorsBehavior) {
  8851. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8852. element.crossOrigin = Tools.CorsBehavior;
  8853. }
  8854. else {
  8855. var result = Tools.CorsBehavior(url);
  8856. if (result) {
  8857. element.crossOrigin = result;
  8858. }
  8859. }
  8860. }
  8861. };
  8862. // External files
  8863. Tools.CleanUrl = function (url) {
  8864. url = url.replace(/#/mg, "%23");
  8865. return url;
  8866. };
  8867. /**
  8868. * Loads an image as an HTMLImageElement.
  8869. * @param input url string, ArrayBuffer, or Blob to load
  8870. * @param onLoad callback called when the image successfully loads
  8871. * @param onError callback called when the image fails to load
  8872. * @param database database for caching
  8873. * @returns the HTMLImageElement of the loaded image
  8874. */
  8875. Tools.LoadImage = function (input, onLoad, onError, database) {
  8876. var url;
  8877. var usingObjectURL = false;
  8878. if (input instanceof ArrayBuffer) {
  8879. url = URL.createObjectURL(new Blob([input]));
  8880. usingObjectURL = true;
  8881. }
  8882. else if (input instanceof Blob) {
  8883. url = URL.createObjectURL(input);
  8884. usingObjectURL = true;
  8885. }
  8886. else {
  8887. url = Tools.CleanUrl(input);
  8888. url = Tools.PreprocessUrl(input);
  8889. }
  8890. var img = new Image();
  8891. Tools.SetCorsBehavior(url, img);
  8892. var loadHandler = function () {
  8893. if (usingObjectURL && img.src) {
  8894. URL.revokeObjectURL(img.src);
  8895. }
  8896. img.removeEventListener("load", loadHandler);
  8897. img.removeEventListener("error", errorHandler);
  8898. onLoad(img);
  8899. };
  8900. var errorHandler = function (err) {
  8901. if (usingObjectURL && img.src) {
  8902. URL.revokeObjectURL(img.src);
  8903. }
  8904. img.removeEventListener("load", loadHandler);
  8905. img.removeEventListener("error", errorHandler);
  8906. Tools.Error("Error while trying to load image: " + input);
  8907. if (onError) {
  8908. onError("Error while trying to load image: " + input, err);
  8909. }
  8910. };
  8911. img.addEventListener("load", loadHandler);
  8912. img.addEventListener("error", errorHandler);
  8913. var noIndexedDB = function () {
  8914. img.src = url;
  8915. };
  8916. var loadFromIndexedDB = function () {
  8917. if (database) {
  8918. database.loadImageFromDB(url, img);
  8919. }
  8920. };
  8921. //ANY database to do!
  8922. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8923. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8924. }
  8925. else {
  8926. if (url.indexOf("file:") !== -1) {
  8927. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8928. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8929. try {
  8930. var blobURL;
  8931. try {
  8932. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8933. }
  8934. catch (ex) {
  8935. // Chrome doesn't support oneTimeOnly parameter
  8936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8937. }
  8938. img.src = blobURL;
  8939. usingObjectURL = true;
  8940. }
  8941. catch (e) {
  8942. img.src = "";
  8943. }
  8944. return img;
  8945. }
  8946. }
  8947. noIndexedDB();
  8948. }
  8949. return img;
  8950. };
  8951. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8952. url = Tools.CleanUrl(url);
  8953. url = Tools.PreprocessUrl(url);
  8954. // If file and file input are set
  8955. if (url.indexOf("file:") !== -1) {
  8956. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8957. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8958. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8959. }
  8960. }
  8961. var loadUrl = Tools.BaseUrl + url;
  8962. var aborted = false;
  8963. var fileRequest = {
  8964. onCompleteObservable: new BABYLON.Observable(),
  8965. abort: function () { return aborted = true; },
  8966. };
  8967. var requestFile = function () {
  8968. var request = new XMLHttpRequest();
  8969. var retryHandle = null;
  8970. fileRequest.abort = function () {
  8971. aborted = true;
  8972. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8973. request.abort();
  8974. }
  8975. if (retryHandle !== null) {
  8976. clearTimeout(retryHandle);
  8977. retryHandle = null;
  8978. }
  8979. };
  8980. var retryLoop = function (retryIndex) {
  8981. request.open('GET', loadUrl, true);
  8982. if (useArrayBuffer) {
  8983. request.responseType = "arraybuffer";
  8984. }
  8985. if (onProgress) {
  8986. request.addEventListener("progress", onProgress);
  8987. }
  8988. var onLoadEnd = function () {
  8989. request.removeEventListener("loadend", onLoadEnd);
  8990. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8991. fileRequest.onCompleteObservable.clear();
  8992. };
  8993. request.addEventListener("loadend", onLoadEnd);
  8994. var onReadyStateChange = function () {
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. // In case of undefined state in some browsers.
  8999. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9000. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9001. request.removeEventListener("readystatechange", onReadyStateChange);
  9002. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9003. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9004. return;
  9005. }
  9006. var retryStrategy = Tools.DefaultRetryStrategy;
  9007. if (retryStrategy) {
  9008. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9009. if (waitTime !== -1) {
  9010. // Prevent the request from completing for retry.
  9011. request.removeEventListener("loadend", onLoadEnd);
  9012. request = new XMLHttpRequest();
  9013. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9014. return;
  9015. }
  9016. }
  9017. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9018. if (onError) {
  9019. onError(request, e);
  9020. }
  9021. else {
  9022. throw e;
  9023. }
  9024. }
  9025. };
  9026. request.addEventListener("readystatechange", onReadyStateChange);
  9027. request.send();
  9028. };
  9029. retryLoop(0);
  9030. };
  9031. // Caching all files
  9032. if (database && database.enableSceneOffline) {
  9033. var noIndexedDB_1 = function () {
  9034. if (!aborted) {
  9035. requestFile();
  9036. }
  9037. };
  9038. var loadFromIndexedDB = function () {
  9039. // TODO: database needs to support aborting and should return a IFileRequest
  9040. if (aborted) {
  9041. return;
  9042. }
  9043. if (database) {
  9044. database.loadFileFromDB(url, function (data) {
  9045. if (!aborted) {
  9046. onSuccess(data);
  9047. }
  9048. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9049. }, onProgress ? function (event) {
  9050. if (!aborted) {
  9051. onProgress(event);
  9052. }
  9053. } : undefined, noIndexedDB_1, useArrayBuffer);
  9054. }
  9055. };
  9056. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9057. }
  9058. else {
  9059. requestFile();
  9060. }
  9061. return fileRequest;
  9062. };
  9063. /**
  9064. * Load a script (identified by an url). When the url returns, the
  9065. * content of this file is added into a new script element, attached to the DOM (body element)
  9066. */
  9067. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9068. var head = document.getElementsByTagName('head')[0];
  9069. var script = document.createElement('script');
  9070. script.type = 'text/javascript';
  9071. script.src = scriptUrl;
  9072. script.onload = function () {
  9073. if (onSuccess) {
  9074. onSuccess();
  9075. }
  9076. };
  9077. script.onerror = function (e) {
  9078. if (onError) {
  9079. onError("Unable to load script '" + scriptUrl + "'", e);
  9080. }
  9081. };
  9082. head.appendChild(script);
  9083. };
  9084. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9085. var reader = new FileReader();
  9086. var request = {
  9087. onCompleteObservable: new BABYLON.Observable(),
  9088. abort: function () { return reader.abort(); },
  9089. };
  9090. reader.onloadend = function (e) {
  9091. request.onCompleteObservable.notifyObservers(request);
  9092. };
  9093. reader.onload = function (e) {
  9094. //target doesn't have result from ts 1.3
  9095. callback(e.target['result']);
  9096. };
  9097. reader.onprogress = progressCallback;
  9098. reader.readAsDataURL(fileToLoad);
  9099. return request;
  9100. };
  9101. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9102. var reader = new FileReader();
  9103. var request = {
  9104. onCompleteObservable: new BABYLON.Observable(),
  9105. abort: function () { return reader.abort(); },
  9106. };
  9107. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9108. reader.onerror = function (e) {
  9109. Tools.Log("Error while reading file: " + fileToLoad.name);
  9110. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9111. };
  9112. reader.onload = function (e) {
  9113. //target doesn't have result from ts 1.3
  9114. callback(e.target['result']);
  9115. };
  9116. if (progressCallBack) {
  9117. reader.onprogress = progressCallBack;
  9118. }
  9119. if (!useArrayBuffer) {
  9120. // Asynchronous read
  9121. reader.readAsText(fileToLoad);
  9122. }
  9123. else {
  9124. reader.readAsArrayBuffer(fileToLoad);
  9125. }
  9126. return request;
  9127. };
  9128. //returns a downloadable url to a file content.
  9129. Tools.FileAsURL = function (content) {
  9130. var fileBlob = new Blob([content]);
  9131. var url = window.URL || window.webkitURL;
  9132. var link = url.createObjectURL(fileBlob);
  9133. return link;
  9134. };
  9135. // Misc.
  9136. Tools.Format = function (value, decimals) {
  9137. if (decimals === void 0) { decimals = 2; }
  9138. return value.toFixed(decimals);
  9139. };
  9140. Tools.CheckExtends = function (v, min, max) {
  9141. if (v.x < min.x)
  9142. min.x = v.x;
  9143. if (v.y < min.y)
  9144. min.y = v.y;
  9145. if (v.z < min.z)
  9146. min.z = v.z;
  9147. if (v.x > max.x)
  9148. max.x = v.x;
  9149. if (v.y > max.y)
  9150. max.y = v.y;
  9151. if (v.z > max.z)
  9152. max.z = v.z;
  9153. };
  9154. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9155. for (var prop in source) {
  9156. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9157. continue;
  9158. }
  9159. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9160. continue;
  9161. }
  9162. var sourceValue = source[prop];
  9163. var typeOfSourceValue = typeof sourceValue;
  9164. if (typeOfSourceValue === "function") {
  9165. continue;
  9166. }
  9167. try {
  9168. if (typeOfSourceValue === "object") {
  9169. if (sourceValue instanceof Array) {
  9170. destination[prop] = [];
  9171. if (sourceValue.length > 0) {
  9172. if (typeof sourceValue[0] == "object") {
  9173. for (var index = 0; index < sourceValue.length; index++) {
  9174. var clonedValue = cloneValue(sourceValue[index], destination);
  9175. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9176. destination[prop].push(clonedValue);
  9177. }
  9178. }
  9179. }
  9180. else {
  9181. destination[prop] = sourceValue.slice(0);
  9182. }
  9183. }
  9184. }
  9185. else {
  9186. destination[prop] = cloneValue(sourceValue, destination);
  9187. }
  9188. }
  9189. else {
  9190. destination[prop] = sourceValue;
  9191. }
  9192. }
  9193. catch (e) {
  9194. // Just ignore error (it could be because of a read-only property)
  9195. }
  9196. }
  9197. };
  9198. Tools.IsEmpty = function (obj) {
  9199. for (var i in obj) {
  9200. if (obj.hasOwnProperty(i)) {
  9201. return false;
  9202. }
  9203. }
  9204. return true;
  9205. };
  9206. Tools.RegisterTopRootEvents = function (events) {
  9207. for (var index = 0; index < events.length; index++) {
  9208. var event = events[index];
  9209. window.addEventListener(event.name, event.handler, false);
  9210. try {
  9211. if (window.parent) {
  9212. window.parent.addEventListener(event.name, event.handler, false);
  9213. }
  9214. }
  9215. catch (e) {
  9216. // Silently fails...
  9217. }
  9218. }
  9219. };
  9220. Tools.UnregisterTopRootEvents = function (events) {
  9221. for (var index = 0; index < events.length; index++) {
  9222. var event = events[index];
  9223. window.removeEventListener(event.name, event.handler);
  9224. try {
  9225. if (window.parent) {
  9226. window.parent.removeEventListener(event.name, event.handler);
  9227. }
  9228. }
  9229. catch (e) {
  9230. // Silently fails...
  9231. }
  9232. }
  9233. };
  9234. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9235. if (mimeType === void 0) { mimeType = "image/png"; }
  9236. // Read the contents of the framebuffer
  9237. var numberOfChannelsByLine = width * 4;
  9238. var halfHeight = height / 2;
  9239. //Reading datas from WebGL
  9240. var data = engine.readPixels(0, 0, width, height);
  9241. //To flip image on Y axis.
  9242. for (var i = 0; i < halfHeight; i++) {
  9243. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9244. var currentCell = j + i * numberOfChannelsByLine;
  9245. var targetLine = height - i - 1;
  9246. var targetCell = j + targetLine * numberOfChannelsByLine;
  9247. var temp = data[currentCell];
  9248. data[currentCell] = data[targetCell];
  9249. data[targetCell] = temp;
  9250. }
  9251. }
  9252. // Create a 2D canvas to store the result
  9253. if (!screenshotCanvas) {
  9254. screenshotCanvas = document.createElement('canvas');
  9255. }
  9256. screenshotCanvas.width = width;
  9257. screenshotCanvas.height = height;
  9258. var context = screenshotCanvas.getContext('2d');
  9259. if (context) {
  9260. // Copy the pixels to a 2D canvas
  9261. var imageData = context.createImageData(width, height);
  9262. var castData = (imageData.data);
  9263. castData.set(data);
  9264. context.putImageData(imageData, 0, 0);
  9265. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9266. }
  9267. };
  9268. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9269. if (mimeType === void 0) { mimeType = "image/png"; }
  9270. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9271. if (successCallback) {
  9272. successCallback(base64Image);
  9273. }
  9274. else {
  9275. // We need HTMLCanvasElement.toBlob for HD screenshots
  9276. if (!screenshotCanvas.toBlob) {
  9277. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9278. screenshotCanvas.toBlob = function (callback, type, quality) {
  9279. var _this = this;
  9280. setTimeout(function () {
  9281. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9282. for (var i = 0; i < len; i++) {
  9283. arr[i] = binStr.charCodeAt(i);
  9284. }
  9285. callback(new Blob([arr], { type: type || 'image/png' }));
  9286. });
  9287. };
  9288. }
  9289. screenshotCanvas.toBlob(function (blob) {
  9290. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9291. if (("download" in document.createElement("a"))) {
  9292. if (!fileName) {
  9293. var date = new Date();
  9294. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9295. fileName = "screenshot_" + stringDate + ".png";
  9296. }
  9297. Tools.Download(blob, fileName);
  9298. }
  9299. else {
  9300. var url = URL.createObjectURL(blob);
  9301. var newWindow = window.open("");
  9302. if (!newWindow)
  9303. return;
  9304. var img = newWindow.document.createElement("img");
  9305. img.onload = function () {
  9306. // no longer need to read the blob so it's revoked
  9307. URL.revokeObjectURL(url);
  9308. };
  9309. img.src = url;
  9310. newWindow.document.body.appendChild(img);
  9311. }
  9312. });
  9313. }
  9314. };
  9315. /**
  9316. * Downloads a blob in the browser
  9317. * @param blob defines the blob to download
  9318. * @param fileName defines the name of the downloaded file
  9319. */
  9320. Tools.Download = function (blob, fileName) {
  9321. var url = window.URL.createObjectURL(blob);
  9322. var a = document.createElement("a");
  9323. document.body.appendChild(a);
  9324. a.style.display = "none";
  9325. a.href = url;
  9326. a.download = fileName;
  9327. a.addEventListener("click", function () {
  9328. if (a.parentElement) {
  9329. a.parentElement.removeChild(a);
  9330. }
  9331. });
  9332. a.click();
  9333. window.URL.revokeObjectURL(url);
  9334. };
  9335. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9336. if (mimeType === void 0) { mimeType = "image/png"; }
  9337. var width;
  9338. var height;
  9339. // If a precision value is specified
  9340. if (size.precision) {
  9341. width = Math.round(engine.getRenderWidth() * size.precision);
  9342. height = Math.round(width / engine.getAspectRatio(camera));
  9343. }
  9344. else if (size.width && size.height) {
  9345. width = size.width;
  9346. height = size.height;
  9347. }
  9348. //If passing only width, computing height to keep display canvas ratio.
  9349. else if (size.width && !size.height) {
  9350. width = size.width;
  9351. height = Math.round(width / engine.getAspectRatio(camera));
  9352. }
  9353. //If passing only height, computing width to keep display canvas ratio.
  9354. else if (size.height && !size.width) {
  9355. height = size.height;
  9356. width = Math.round(height * engine.getAspectRatio(camera));
  9357. }
  9358. //Assuming here that "size" parameter is a number
  9359. else if (!isNaN(size)) {
  9360. height = size;
  9361. width = size;
  9362. }
  9363. else {
  9364. Tools.Error("Invalid 'size' parameter !");
  9365. return;
  9366. }
  9367. if (!screenshotCanvas) {
  9368. screenshotCanvas = document.createElement('canvas');
  9369. }
  9370. screenshotCanvas.width = width;
  9371. screenshotCanvas.height = height;
  9372. var renderContext = screenshotCanvas.getContext("2d");
  9373. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9374. var newWidth = width;
  9375. var newHeight = newWidth / ratio;
  9376. if (newHeight > height) {
  9377. newHeight = height;
  9378. newWidth = newHeight * ratio;
  9379. }
  9380. var offsetX = Math.max(0, width - newWidth) / 2;
  9381. var offsetY = Math.max(0, height - newHeight) / 2;
  9382. var renderingCanvas = engine.getRenderingCanvas();
  9383. if (renderContext && renderingCanvas) {
  9384. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9385. }
  9386. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9387. };
  9388. /**
  9389. * Generates an image screenshot from the specified camera.
  9390. *
  9391. * @param engine The engine to use for rendering
  9392. * @param camera The camera to use for rendering
  9393. * @param size This parameter can be set to a single number or to an object with the
  9394. * following (optional) properties: precision, width, height. If a single number is passed,
  9395. * it will be used for both width and height. If an object is passed, the screenshot size
  9396. * will be derived from the parameters. The precision property is a multiplier allowing
  9397. * rendering at a higher or lower resolution.
  9398. * @param successCallback The callback receives a single parameter which contains the
  9399. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9400. * src parameter of an <img> to display it.
  9401. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9402. * Check your browser for supported MIME types.
  9403. * @param samples Texture samples (default: 1)
  9404. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9405. * @param fileName A name for for the downloaded file.
  9406. * @constructor
  9407. */
  9408. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9409. if (mimeType === void 0) { mimeType = "image/png"; }
  9410. if (samples === void 0) { samples = 1; }
  9411. if (antialiasing === void 0) { antialiasing = false; }
  9412. var width;
  9413. var height;
  9414. //If a precision value is specified
  9415. if (size.precision) {
  9416. width = Math.round(engine.getRenderWidth() * size.precision);
  9417. height = Math.round(width / engine.getAspectRatio(camera));
  9418. size = { width: width, height: height };
  9419. }
  9420. else if (size.width && size.height) {
  9421. width = size.width;
  9422. height = size.height;
  9423. }
  9424. //If passing only width, computing height to keep display canvas ratio.
  9425. else if (size.width && !size.height) {
  9426. width = size.width;
  9427. height = Math.round(width / engine.getAspectRatio(camera));
  9428. size = { width: width, height: height };
  9429. }
  9430. //If passing only height, computing width to keep display canvas ratio.
  9431. else if (size.height && !size.width) {
  9432. height = size.height;
  9433. width = Math.round(height * engine.getAspectRatio(camera));
  9434. size = { width: width, height: height };
  9435. }
  9436. //Assuming here that "size" parameter is a number
  9437. else if (!isNaN(size)) {
  9438. height = size;
  9439. width = size;
  9440. }
  9441. else {
  9442. Tools.Error("Invalid 'size' parameter !");
  9443. return;
  9444. }
  9445. var scene = camera.getScene();
  9446. var previousCamera = null;
  9447. if (scene.activeCamera !== camera) {
  9448. previousCamera = scene.activeCamera;
  9449. scene.activeCamera = camera;
  9450. }
  9451. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9452. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9453. texture.renderList = null;
  9454. texture.samples = samples;
  9455. if (antialiasing) {
  9456. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9457. }
  9458. texture.onAfterRenderObservable.add(function () {
  9459. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9460. });
  9461. scene.incrementRenderId();
  9462. scene.resetCachedMaterial();
  9463. texture.render(true);
  9464. texture.dispose();
  9465. if (previousCamera) {
  9466. scene.activeCamera = previousCamera;
  9467. }
  9468. camera.getProjectionMatrix(true); // Force cache refresh;
  9469. };
  9470. // XHR response validator for local file scenario
  9471. Tools.ValidateXHRData = function (xhr, dataType) {
  9472. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9473. if (dataType === void 0) { dataType = 7; }
  9474. try {
  9475. if (dataType & 1) {
  9476. if (xhr.responseText && xhr.responseText.length > 0) {
  9477. return true;
  9478. }
  9479. else if (dataType === 1) {
  9480. return false;
  9481. }
  9482. }
  9483. if (dataType & 2) {
  9484. // Check header width and height since there is no "TGA" magic number
  9485. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9486. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9487. return true;
  9488. }
  9489. else if (dataType === 2) {
  9490. return false;
  9491. }
  9492. }
  9493. if (dataType & 4) {
  9494. // Check for the "DDS" magic number
  9495. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9496. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9497. return true;
  9498. }
  9499. else {
  9500. return false;
  9501. }
  9502. }
  9503. }
  9504. catch (e) {
  9505. // Global protection
  9506. }
  9507. return false;
  9508. };
  9509. /**
  9510. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9511. * Be aware Math.random() could cause collisions, but:
  9512. * "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"
  9513. */
  9514. Tools.RandomId = function () {
  9515. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9516. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9517. return v.toString(16);
  9518. });
  9519. };
  9520. /**
  9521. * Test if the given uri is a base64 string.
  9522. * @param uri The uri to test
  9523. * @return True if the uri is a base64 string or false otherwise.
  9524. */
  9525. Tools.IsBase64 = function (uri) {
  9526. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9527. };
  9528. /**
  9529. * Decode the given base64 uri.
  9530. * @param uri The uri to decode
  9531. * @return The decoded base64 data.
  9532. */
  9533. Tools.DecodeBase64 = function (uri) {
  9534. var decodedString = atob(uri.split(",")[1]);
  9535. var bufferLength = decodedString.length;
  9536. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9537. for (var i = 0; i < bufferLength; i++) {
  9538. bufferView[i] = decodedString.charCodeAt(i);
  9539. }
  9540. return bufferView.buffer;
  9541. };
  9542. Object.defineProperty(Tools, "NoneLogLevel", {
  9543. get: function () {
  9544. return Tools._NoneLogLevel;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(Tools, "MessageLogLevel", {
  9550. get: function () {
  9551. return Tools._MessageLogLevel;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(Tools, "WarningLogLevel", {
  9557. get: function () {
  9558. return Tools._WarningLogLevel;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Tools, "ErrorLogLevel", {
  9564. get: function () {
  9565. return Tools._ErrorLogLevel;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Tools, "AllLogLevel", {
  9571. get: function () {
  9572. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Tools._AddLogEntry = function (entry) {
  9578. Tools._LogCache = entry + Tools._LogCache;
  9579. if (Tools.OnNewCacheEntry) {
  9580. Tools.OnNewCacheEntry(entry);
  9581. }
  9582. };
  9583. Tools._FormatMessage = function (message) {
  9584. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9585. var date = new Date();
  9586. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9587. };
  9588. Tools._LogDisabled = function (message) {
  9589. // nothing to do
  9590. };
  9591. Tools._LogEnabled = function (message) {
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.log("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Tools._WarnDisabled = function (message) {
  9598. // nothing to do
  9599. };
  9600. Tools._WarnEnabled = function (message) {
  9601. var formattedMessage = Tools._FormatMessage(message);
  9602. console.warn("BJS - " + formattedMessage);
  9603. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9604. Tools._AddLogEntry(entry);
  9605. };
  9606. Tools._ErrorDisabled = function (message) {
  9607. // nothing to do
  9608. };
  9609. Tools._ErrorEnabled = function (message) {
  9610. Tools.errorsCount++;
  9611. var formattedMessage = Tools._FormatMessage(message);
  9612. console.error("BJS - " + formattedMessage);
  9613. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9614. Tools._AddLogEntry(entry);
  9615. };
  9616. Object.defineProperty(Tools, "LogCache", {
  9617. get: function () {
  9618. return Tools._LogCache;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Tools.ClearLogCache = function () {
  9624. Tools._LogCache = "";
  9625. Tools.errorsCount = 0;
  9626. };
  9627. Object.defineProperty(Tools, "LogLevels", {
  9628. set: function (level) {
  9629. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9630. Tools.Log = Tools._LogEnabled;
  9631. }
  9632. else {
  9633. Tools.Log = Tools._LogDisabled;
  9634. }
  9635. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9636. Tools.Warn = Tools._WarnEnabled;
  9637. }
  9638. else {
  9639. Tools.Warn = Tools._WarnDisabled;
  9640. }
  9641. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9642. Tools.Error = Tools._ErrorEnabled;
  9643. }
  9644. else {
  9645. Tools.Error = Tools._ErrorDisabled;
  9646. }
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Tools.IsWindowObjectExist = function () {
  9652. return (typeof window) !== "undefined";
  9653. };
  9654. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9655. get: function () {
  9656. return Tools._PerformanceNoneLogLevel;
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9662. get: function () {
  9663. return Tools._PerformanceUserMarkLogLevel;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9669. get: function () {
  9670. return Tools._PerformanceConsoleLogLevel;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9676. set: function (level) {
  9677. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9678. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9679. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9680. return;
  9681. }
  9682. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9683. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9684. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9685. return;
  9686. }
  9687. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9688. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9694. };
  9695. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9696. };
  9697. Tools._StartUserMark = function (counterName, condition) {
  9698. if (condition === void 0) { condition = true; }
  9699. if (!Tools._performance) {
  9700. if (!Tools.IsWindowObjectExist()) {
  9701. return;
  9702. }
  9703. Tools._performance = window.performance;
  9704. }
  9705. if (!condition || !Tools._performance.mark) {
  9706. return;
  9707. }
  9708. Tools._performance.mark(counterName + "-Begin");
  9709. };
  9710. Tools._EndUserMark = function (counterName, condition) {
  9711. if (condition === void 0) { condition = true; }
  9712. if (!condition || !Tools._performance.mark) {
  9713. return;
  9714. }
  9715. Tools._performance.mark(counterName + "-End");
  9716. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9717. };
  9718. Tools._StartPerformanceConsole = function (counterName, condition) {
  9719. if (condition === void 0) { condition = true; }
  9720. if (!condition) {
  9721. return;
  9722. }
  9723. Tools._StartUserMark(counterName, condition);
  9724. if (console.time) {
  9725. console.time(counterName);
  9726. }
  9727. };
  9728. Tools._EndPerformanceConsole = function (counterName, condition) {
  9729. if (condition === void 0) { condition = true; }
  9730. if (!condition) {
  9731. return;
  9732. }
  9733. Tools._EndUserMark(counterName, condition);
  9734. if (console.time) {
  9735. console.timeEnd(counterName);
  9736. }
  9737. };
  9738. Object.defineProperty(Tools, "Now", {
  9739. get: function () {
  9740. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9741. return window.performance.now();
  9742. }
  9743. return Date.now();
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. /**
  9749. * This method will return the name of the class used to create the instance of the given object.
  9750. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9751. * @param object the object to get the class name from
  9752. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9753. */
  9754. Tools.GetClassName = function (object, isType) {
  9755. if (isType === void 0) { isType = false; }
  9756. var name = null;
  9757. if (!isType && object.getClassName) {
  9758. name = object.getClassName();
  9759. }
  9760. else {
  9761. if (object instanceof Object) {
  9762. var classObj = isType ? object : Object.getPrototypeOf(object);
  9763. name = classObj.constructor["__bjsclassName__"];
  9764. }
  9765. if (!name) {
  9766. name = typeof object;
  9767. }
  9768. }
  9769. return name;
  9770. };
  9771. Tools.First = function (array, predicate) {
  9772. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9773. var el = array_1[_i];
  9774. if (predicate(el)) {
  9775. return el;
  9776. }
  9777. }
  9778. return null;
  9779. };
  9780. /**
  9781. * This method will return the name of the full name of the class, including its owning module (if any).
  9782. * 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).
  9783. * @param object the object to get the class name from
  9784. * @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.
  9785. */
  9786. Tools.getFullClassName = function (object, isType) {
  9787. if (isType === void 0) { isType = false; }
  9788. var className = null;
  9789. var moduleName = null;
  9790. if (!isType && object.getClassName) {
  9791. className = object.getClassName();
  9792. }
  9793. else {
  9794. if (object instanceof Object) {
  9795. var classObj = isType ? object : Object.getPrototypeOf(object);
  9796. className = classObj.constructor["__bjsclassName__"];
  9797. moduleName = classObj.constructor["__bjsmoduleName__"];
  9798. }
  9799. if (!className) {
  9800. className = typeof object;
  9801. }
  9802. }
  9803. if (!className) {
  9804. return null;
  9805. }
  9806. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9807. };
  9808. /**
  9809. * 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.
  9810. * @param array
  9811. */
  9812. Tools.arrayOrStringFeeder = function (array) {
  9813. return function (index) {
  9814. if (index >= array.length) {
  9815. return null;
  9816. }
  9817. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9818. if (val && val.getHashCode) {
  9819. val = val.getHashCode();
  9820. }
  9821. if (typeof val === "string") {
  9822. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9823. }
  9824. return val;
  9825. };
  9826. };
  9827. /**
  9828. * Compute the hashCode of a stream of number
  9829. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9830. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9831. * @return the hash code computed
  9832. */
  9833. Tools.hashCodeFromStream = function (feeder) {
  9834. // Based from here: http://stackoverflow.com/a/7616484/802124
  9835. var hash = 0;
  9836. var index = 0;
  9837. var chr = feeder(index++);
  9838. while (chr != null) {
  9839. hash = ((hash << 5) - hash) + chr;
  9840. hash |= 0; // Convert to 32bit integer
  9841. chr = feeder(index++);
  9842. }
  9843. return hash;
  9844. };
  9845. /**
  9846. * Returns a promise that resolves after the given amount of time.
  9847. * @param delay Number of milliseconds to delay
  9848. * @returns Promise that resolves after the given amount of time
  9849. */
  9850. Tools.DelayAsync = function (delay) {
  9851. return new Promise(function (resolve) {
  9852. setTimeout(function () {
  9853. resolve();
  9854. }, delay);
  9855. });
  9856. };
  9857. Tools.BaseUrl = "";
  9858. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9859. /**
  9860. * Default behaviour for cors in the application.
  9861. * It can be a string if the expected behavior is identical in the entire app.
  9862. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9863. */
  9864. Tools.CorsBehavior = "anonymous";
  9865. Tools.UseFallbackTexture = true;
  9866. /**
  9867. * Use this object to register external classes like custom textures or material
  9868. * to allow the laoders to instantiate them
  9869. */
  9870. Tools.RegisteredExternalClasses = {};
  9871. // Used in case of a texture loading problem
  9872. 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";
  9873. Tools._tmpFloatArray = new Float32Array(1);
  9874. Tools.PreprocessUrl = function (url) {
  9875. return url;
  9876. };
  9877. // Logs
  9878. Tools._NoneLogLevel = 0;
  9879. Tools._MessageLogLevel = 1;
  9880. Tools._WarningLogLevel = 2;
  9881. Tools._ErrorLogLevel = 4;
  9882. Tools._LogCache = "";
  9883. Tools.errorsCount = 0;
  9884. Tools.Log = Tools._LogEnabled;
  9885. Tools.Warn = Tools._WarnEnabled;
  9886. Tools.Error = Tools._ErrorEnabled;
  9887. // Performances
  9888. Tools._PerformanceNoneLogLevel = 0;
  9889. Tools._PerformanceUserMarkLogLevel = 1;
  9890. Tools._PerformanceConsoleLogLevel = 2;
  9891. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9892. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9893. return Tools;
  9894. }());
  9895. BABYLON.Tools = Tools;
  9896. /**
  9897. * This class is used to track a performance counter which is number based.
  9898. * The user has access to many properties which give statistics of different nature
  9899. *
  9900. * The implementer can track two kinds of Performance Counter: time and count
  9901. * 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.
  9902. * 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.
  9903. */
  9904. var PerfCounter = /** @class */ (function () {
  9905. function PerfCounter() {
  9906. this._startMonitoringTime = 0;
  9907. this._min = 0;
  9908. this._max = 0;
  9909. this._average = 0;
  9910. this._lastSecAverage = 0;
  9911. this._current = 0;
  9912. this._totalValueCount = 0;
  9913. this._totalAccumulated = 0;
  9914. this._lastSecAccumulated = 0;
  9915. this._lastSecTime = 0;
  9916. this._lastSecValueCount = 0;
  9917. }
  9918. Object.defineProperty(PerfCounter.prototype, "min", {
  9919. /**
  9920. * Returns the smallest value ever
  9921. */
  9922. get: function () {
  9923. return this._min;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(PerfCounter.prototype, "max", {
  9929. /**
  9930. * Returns the biggest value ever
  9931. */
  9932. get: function () {
  9933. return this._max;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(PerfCounter.prototype, "average", {
  9939. /**
  9940. * Returns the average value since the performance counter is running
  9941. */
  9942. get: function () {
  9943. return this._average;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9949. /**
  9950. * Returns the average value of the last second the counter was monitored
  9951. */
  9952. get: function () {
  9953. return this._lastSecAverage;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(PerfCounter.prototype, "current", {
  9959. /**
  9960. * Returns the current value
  9961. */
  9962. get: function () {
  9963. return this._current;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(PerfCounter.prototype, "total", {
  9969. get: function () {
  9970. return this._totalAccumulated;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "count", {
  9976. get: function () {
  9977. return this._totalValueCount;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. /**
  9983. * Call this method to start monitoring a new frame.
  9984. * 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.
  9985. */
  9986. PerfCounter.prototype.fetchNewFrame = function () {
  9987. this._totalValueCount++;
  9988. this._current = 0;
  9989. this._lastSecValueCount++;
  9990. };
  9991. /**
  9992. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9993. * @param newCount the count value to add to the monitored count
  9994. * @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.
  9995. */
  9996. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9997. if (!PerfCounter.Enabled) {
  9998. return;
  9999. }
  10000. this._current += newCount;
  10001. if (fetchResult) {
  10002. this._fetchResult();
  10003. }
  10004. };
  10005. /**
  10006. * Start monitoring this performance counter
  10007. */
  10008. PerfCounter.prototype.beginMonitoring = function () {
  10009. if (!PerfCounter.Enabled) {
  10010. return;
  10011. }
  10012. this._startMonitoringTime = Tools.Now;
  10013. };
  10014. /**
  10015. * Compute the time lapsed since the previous beginMonitoring() call.
  10016. * @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
  10017. */
  10018. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10019. if (newFrame === void 0) { newFrame = true; }
  10020. if (!PerfCounter.Enabled) {
  10021. return;
  10022. }
  10023. if (newFrame) {
  10024. this.fetchNewFrame();
  10025. }
  10026. var currentTime = Tools.Now;
  10027. this._current = currentTime - this._startMonitoringTime;
  10028. if (newFrame) {
  10029. this._fetchResult();
  10030. }
  10031. };
  10032. PerfCounter.prototype._fetchResult = function () {
  10033. this._totalAccumulated += this._current;
  10034. this._lastSecAccumulated += this._current;
  10035. // Min/Max update
  10036. this._min = Math.min(this._min, this._current);
  10037. this._max = Math.max(this._max, this._current);
  10038. this._average = this._totalAccumulated / this._totalValueCount;
  10039. // Reset last sec?
  10040. var now = Tools.Now;
  10041. if ((now - this._lastSecTime) > 1000) {
  10042. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10043. this._lastSecTime = now;
  10044. this._lastSecAccumulated = 0;
  10045. this._lastSecValueCount = 0;
  10046. }
  10047. };
  10048. PerfCounter.Enabled = true;
  10049. return PerfCounter;
  10050. }());
  10051. BABYLON.PerfCounter = PerfCounter;
  10052. /**
  10053. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10054. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10055. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10056. * @param name The name of the class, case should be preserved
  10057. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10058. */
  10059. function className(name, module) {
  10060. return function (target) {
  10061. target["__bjsclassName__"] = name;
  10062. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10063. };
  10064. }
  10065. BABYLON.className = className;
  10066. /**
  10067. * An implementation of a loop for asynchronous functions.
  10068. */
  10069. var AsyncLoop = /** @class */ (function () {
  10070. /**
  10071. * Constroctor.
  10072. * @param iterations the number of iterations.
  10073. * @param _fn the function to run each iteration
  10074. * @param _successCallback the callback that will be called upon succesful execution
  10075. * @param offset starting offset.
  10076. */
  10077. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10078. if (offset === void 0) { offset = 0; }
  10079. this.iterations = iterations;
  10080. this._fn = _fn;
  10081. this._successCallback = _successCallback;
  10082. this.index = offset - 1;
  10083. this._done = false;
  10084. }
  10085. /**
  10086. * Execute the next iteration. Must be called after the last iteration was finished.
  10087. */
  10088. AsyncLoop.prototype.executeNext = function () {
  10089. if (!this._done) {
  10090. if (this.index + 1 < this.iterations) {
  10091. ++this.index;
  10092. this._fn(this);
  10093. }
  10094. else {
  10095. this.breakLoop();
  10096. }
  10097. }
  10098. };
  10099. /**
  10100. * Break the loop and run the success callback.
  10101. */
  10102. AsyncLoop.prototype.breakLoop = function () {
  10103. this._done = true;
  10104. this._successCallback();
  10105. };
  10106. /**
  10107. * Helper function
  10108. */
  10109. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10110. if (offset === void 0) { offset = 0; }
  10111. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10112. loop.executeNext();
  10113. return loop;
  10114. };
  10115. /**
  10116. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10117. * @param iterations total number of iterations
  10118. * @param syncedIterations number of synchronous iterations in each async iteration.
  10119. * @param fn the function to call each iteration.
  10120. * @param callback a success call back that will be called when iterating stops.
  10121. * @param breakFunction a break condition (optional)
  10122. * @param timeout timeout settings for the setTimeout function. default - 0.
  10123. * @constructor
  10124. */
  10125. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10126. if (timeout === void 0) { timeout = 0; }
  10127. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10128. if (breakFunction && breakFunction())
  10129. loop.breakLoop();
  10130. else {
  10131. setTimeout(function () {
  10132. for (var i = 0; i < syncedIterations; ++i) {
  10133. var iteration = (loop.index * syncedIterations) + i;
  10134. if (iteration >= iterations)
  10135. break;
  10136. fn(iteration);
  10137. if (breakFunction && breakFunction()) {
  10138. loop.breakLoop();
  10139. break;
  10140. }
  10141. }
  10142. loop.executeNext();
  10143. }, timeout);
  10144. }
  10145. }, callback);
  10146. };
  10147. return AsyncLoop;
  10148. }());
  10149. BABYLON.AsyncLoop = AsyncLoop;
  10150. })(BABYLON || (BABYLON = {}));
  10151. //# sourceMappingURL=babylon.tools.js.map
  10152. var BABYLON;
  10153. (function (BABYLON) {
  10154. var PromiseStates;
  10155. (function (PromiseStates) {
  10156. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10157. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10158. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10159. })(PromiseStates || (PromiseStates = {}));
  10160. var FulFillmentAgregator = /** @class */ (function () {
  10161. function FulFillmentAgregator() {
  10162. this.count = 0;
  10163. this.target = 0;
  10164. this.results = [];
  10165. }
  10166. return FulFillmentAgregator;
  10167. }());
  10168. var InternalPromise = /** @class */ (function () {
  10169. function InternalPromise(resolver) {
  10170. var _this = this;
  10171. this._state = PromiseStates.Pending;
  10172. this._children = new Array();
  10173. this._rejectWasConsumed = false;
  10174. if (!resolver) {
  10175. return;
  10176. }
  10177. try {
  10178. resolver(function (value) {
  10179. _this._resolve(value);
  10180. }, function (reason) {
  10181. _this._reject(reason);
  10182. });
  10183. }
  10184. catch (e) {
  10185. this._reject(e);
  10186. }
  10187. }
  10188. Object.defineProperty(InternalPromise.prototype, "_result", {
  10189. get: function () {
  10190. return this._resultValue;
  10191. },
  10192. set: function (value) {
  10193. this._resultValue = value;
  10194. if (this._parent && this._parent._result === undefined) {
  10195. this._parent._result = value;
  10196. }
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. InternalPromise.prototype.catch = function (onRejected) {
  10202. return this.then(undefined, onRejected);
  10203. };
  10204. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10205. var _this = this;
  10206. var newPromise = new InternalPromise();
  10207. newPromise._onFulfilled = onFulfilled;
  10208. newPromise._onRejected = onRejected;
  10209. // Composition
  10210. this._children.push(newPromise);
  10211. newPromise._parent = this;
  10212. if (this._state !== PromiseStates.Pending) {
  10213. BABYLON.Tools.SetImmediate(function () {
  10214. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10215. var returnedValue = newPromise._resolve(_this._result);
  10216. if (returnedValue !== undefined && returnedValue !== null) {
  10217. if (returnedValue._state !== undefined) {
  10218. var returnedPromise = returnedValue;
  10219. newPromise._children.push(returnedPromise);
  10220. returnedPromise._parent = newPromise;
  10221. newPromise = returnedPromise;
  10222. }
  10223. else {
  10224. newPromise._result = returnedValue;
  10225. }
  10226. }
  10227. }
  10228. else {
  10229. newPromise._reject(_this._reason);
  10230. }
  10231. });
  10232. }
  10233. return newPromise;
  10234. };
  10235. InternalPromise.prototype._moveChildren = function (children) {
  10236. var _this = this;
  10237. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10238. this._children.forEach(function (child) {
  10239. child._parent = _this;
  10240. });
  10241. if (this._state === PromiseStates.Fulfilled) {
  10242. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10243. var child = _b[_i];
  10244. child._resolve(this._result);
  10245. }
  10246. }
  10247. else if (this._state === PromiseStates.Rejected) {
  10248. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10249. var child = _d[_c];
  10250. child._reject(this._reason);
  10251. }
  10252. }
  10253. var _a;
  10254. };
  10255. InternalPromise.prototype._resolve = function (value) {
  10256. try {
  10257. this._state = PromiseStates.Fulfilled;
  10258. var returnedValue = null;
  10259. if (this._onFulfilled) {
  10260. returnedValue = this._onFulfilled(value);
  10261. }
  10262. if (returnedValue !== undefined && returnedValue !== null) {
  10263. if (returnedValue._state !== undefined) {
  10264. // Transmit children
  10265. var returnedPromise = returnedValue;
  10266. returnedPromise._parent = this;
  10267. returnedPromise._moveChildren(this._children);
  10268. value = returnedPromise._result;
  10269. }
  10270. else {
  10271. value = returnedValue;
  10272. }
  10273. }
  10274. this._result = value;
  10275. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10276. var child = _a[_i];
  10277. child._resolve(value);
  10278. }
  10279. this._children.length = 0;
  10280. delete this._onFulfilled;
  10281. delete this._onRejected;
  10282. }
  10283. catch (e) {
  10284. this._reject(e, true);
  10285. }
  10286. };
  10287. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10288. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10289. this._state = PromiseStates.Rejected;
  10290. this._reason = reason;
  10291. if (this._onRejected && !onLocalThrow) {
  10292. try {
  10293. this._onRejected(reason);
  10294. this._rejectWasConsumed = true;
  10295. }
  10296. catch (e) {
  10297. reason = e;
  10298. }
  10299. }
  10300. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10301. var child = _a[_i];
  10302. if (this._rejectWasConsumed) {
  10303. child._resolve(null);
  10304. }
  10305. else {
  10306. child._reject(reason);
  10307. }
  10308. }
  10309. this._children.length = 0;
  10310. delete this._onFulfilled;
  10311. delete this._onRejected;
  10312. };
  10313. InternalPromise.resolve = function (value) {
  10314. var newPromise = new InternalPromise();
  10315. newPromise._resolve(value);
  10316. return newPromise;
  10317. };
  10318. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10319. promise.then(function (value) {
  10320. agregator.results[index] = value;
  10321. agregator.count++;
  10322. if (agregator.count === agregator.target) {
  10323. agregator.rootPromise._resolve(agregator.results);
  10324. }
  10325. return null;
  10326. }, function (reason) {
  10327. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10328. agregator.rootPromise._reject(reason);
  10329. }
  10330. });
  10331. };
  10332. InternalPromise.all = function (promises) {
  10333. var newPromise = new InternalPromise();
  10334. var agregator = new FulFillmentAgregator();
  10335. agregator.target = promises.length;
  10336. agregator.rootPromise = newPromise;
  10337. if (promises.length) {
  10338. for (var index = 0; index < promises.length; index++) {
  10339. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10340. }
  10341. }
  10342. else {
  10343. newPromise._resolve([]);
  10344. }
  10345. return newPromise;
  10346. };
  10347. InternalPromise.race = function (promises) {
  10348. var newPromise = new InternalPromise();
  10349. if (promises.length) {
  10350. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10351. var promise = promises_1[_i];
  10352. promise.then(function (value) {
  10353. if (newPromise) {
  10354. newPromise._resolve(value);
  10355. newPromise = null;
  10356. }
  10357. return null;
  10358. }, function (reason) {
  10359. if (newPromise) {
  10360. newPromise._reject(reason);
  10361. newPromise = null;
  10362. }
  10363. });
  10364. }
  10365. }
  10366. return newPromise;
  10367. };
  10368. return InternalPromise;
  10369. }());
  10370. /**
  10371. * Helper class that provides a small promise polyfill
  10372. */
  10373. var PromisePolyfill = /** @class */ (function () {
  10374. function PromisePolyfill() {
  10375. }
  10376. /**
  10377. * Static function used to check if the polyfill is required
  10378. * If this is the case then the function will inject the polyfill to window.Promise
  10379. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10380. */
  10381. PromisePolyfill.Apply = function (force) {
  10382. if (force === void 0) { force = false; }
  10383. if (force || typeof Promise === 'undefined') {
  10384. var root = window;
  10385. root.Promise = InternalPromise;
  10386. }
  10387. };
  10388. return PromisePolyfill;
  10389. }());
  10390. BABYLON.PromisePolyfill = PromisePolyfill;
  10391. })(BABYLON || (BABYLON = {}));
  10392. //# sourceMappingURL=babylon.promise.js.map
  10393. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10394. var BABYLON;
  10395. (function (BABYLON) {
  10396. /**
  10397. * Helper class to push actions to a pool of workers.
  10398. */
  10399. var WorkerPool = /** @class */ (function () {
  10400. /**
  10401. * Constructor
  10402. * @param workers Array of workers to use for actions
  10403. */
  10404. function WorkerPool(workers) {
  10405. this._pendingActions = new Array();
  10406. this._workerInfos = workers.map(function (worker) { return ({
  10407. worker: worker,
  10408. active: false
  10409. }); });
  10410. }
  10411. /**
  10412. * Terminates all workers and clears any pending actions.
  10413. */
  10414. WorkerPool.prototype.dispose = function () {
  10415. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10416. var workerInfo = _a[_i];
  10417. workerInfo.worker.terminate();
  10418. }
  10419. delete this._workerInfos;
  10420. delete this._pendingActions;
  10421. };
  10422. /**
  10423. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10424. * pended until a worker has completed its action.
  10425. * @param action The action to perform. Call onComplete when the action is complete.
  10426. */
  10427. WorkerPool.prototype.push = function (action) {
  10428. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10429. var workerInfo = _a[_i];
  10430. if (!workerInfo.active) {
  10431. this._execute(workerInfo, action);
  10432. return;
  10433. }
  10434. }
  10435. this._pendingActions.push(action);
  10436. };
  10437. WorkerPool.prototype._execute = function (workerInfo, action) {
  10438. var _this = this;
  10439. workerInfo.active = true;
  10440. action(workerInfo.worker, function () {
  10441. workerInfo.active = false;
  10442. var nextAction = _this._pendingActions.shift();
  10443. if (nextAction) {
  10444. _this._execute(workerInfo, nextAction);
  10445. }
  10446. });
  10447. };
  10448. return WorkerPool;
  10449. }());
  10450. BABYLON.WorkerPool = WorkerPool;
  10451. })(BABYLON || (BABYLON = {}));
  10452. //# sourceMappingURL=babylon.workerPool.js.map
  10453. var BABYLON;
  10454. (function (BABYLON) {
  10455. /**
  10456. * @hidden
  10457. **/
  10458. var _AlphaState = /** @class */ (function () {
  10459. /**
  10460. * Initializes the state.
  10461. */
  10462. function _AlphaState() {
  10463. this._isAlphaBlendDirty = false;
  10464. this._isBlendFunctionParametersDirty = false;
  10465. this._isBlendEquationParametersDirty = false;
  10466. this._isBlendConstantsDirty = false;
  10467. this._alphaBlend = false;
  10468. this._blendFunctionParameters = new Array(4);
  10469. this._blendEquationParameters = new Array(2);
  10470. this._blendConstants = new Array(4);
  10471. this.reset();
  10472. }
  10473. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10474. get: function () {
  10475. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10476. },
  10477. enumerable: true,
  10478. configurable: true
  10479. });
  10480. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10481. get: function () {
  10482. return this._alphaBlend;
  10483. },
  10484. set: function (value) {
  10485. if (this._alphaBlend === value) {
  10486. return;
  10487. }
  10488. this._alphaBlend = value;
  10489. this._isAlphaBlendDirty = true;
  10490. },
  10491. enumerable: true,
  10492. configurable: true
  10493. });
  10494. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10495. if (this._blendConstants[0] === r &&
  10496. this._blendConstants[1] === g &&
  10497. this._blendConstants[2] === b &&
  10498. this._blendConstants[3] === a) {
  10499. return;
  10500. }
  10501. this._blendConstants[0] = r;
  10502. this._blendConstants[1] = g;
  10503. this._blendConstants[2] = b;
  10504. this._blendConstants[3] = a;
  10505. this._isBlendConstantsDirty = true;
  10506. };
  10507. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10508. if (this._blendFunctionParameters[0] === value0 &&
  10509. this._blendFunctionParameters[1] === value1 &&
  10510. this._blendFunctionParameters[2] === value2 &&
  10511. this._blendFunctionParameters[3] === value3) {
  10512. return;
  10513. }
  10514. this._blendFunctionParameters[0] = value0;
  10515. this._blendFunctionParameters[1] = value1;
  10516. this._blendFunctionParameters[2] = value2;
  10517. this._blendFunctionParameters[3] = value3;
  10518. this._isBlendFunctionParametersDirty = true;
  10519. };
  10520. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10521. if (this._blendEquationParameters[0] === rgb &&
  10522. this._blendEquationParameters[1] === alpha) {
  10523. return;
  10524. }
  10525. this._blendEquationParameters[0] = rgb;
  10526. this._blendEquationParameters[1] = alpha;
  10527. this._isBlendEquationParametersDirty = true;
  10528. };
  10529. _AlphaState.prototype.reset = function () {
  10530. this._alphaBlend = false;
  10531. this._blendFunctionParameters[0] = null;
  10532. this._blendFunctionParameters[1] = null;
  10533. this._blendFunctionParameters[2] = null;
  10534. this._blendFunctionParameters[3] = null;
  10535. this._blendEquationParameters[0] = null;
  10536. this._blendEquationParameters[1] = null;
  10537. this._blendConstants[0] = null;
  10538. this._blendConstants[1] = null;
  10539. this._blendConstants[2] = null;
  10540. this._blendConstants[3] = null;
  10541. this._isAlphaBlendDirty = true;
  10542. this._isBlendFunctionParametersDirty = false;
  10543. this._isBlendEquationParametersDirty = false;
  10544. this._isBlendConstantsDirty = false;
  10545. };
  10546. _AlphaState.prototype.apply = function (gl) {
  10547. if (!this.isDirty) {
  10548. return;
  10549. }
  10550. // Alpha blend
  10551. if (this._isAlphaBlendDirty) {
  10552. if (this._alphaBlend) {
  10553. gl.enable(gl.BLEND);
  10554. }
  10555. else {
  10556. gl.disable(gl.BLEND);
  10557. }
  10558. this._isAlphaBlendDirty = false;
  10559. }
  10560. // Alpha function
  10561. if (this._isBlendFunctionParametersDirty) {
  10562. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10563. this._isBlendFunctionParametersDirty = false;
  10564. }
  10565. // Alpha equation
  10566. if (this._isBlendEquationParametersDirty) {
  10567. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10568. this._isBlendEquationParametersDirty = false;
  10569. }
  10570. // Constants
  10571. if (this._isBlendConstantsDirty) {
  10572. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10573. this._isBlendConstantsDirty = false;
  10574. }
  10575. };
  10576. return _AlphaState;
  10577. }());
  10578. BABYLON._AlphaState = _AlphaState;
  10579. })(BABYLON || (BABYLON = {}));
  10580. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10581. var BABYLON;
  10582. (function (BABYLON) {
  10583. /**
  10584. * @hidden
  10585. **/
  10586. var _DepthCullingState = /** @class */ (function () {
  10587. /**
  10588. * Initializes the state.
  10589. */
  10590. function _DepthCullingState() {
  10591. this._isDepthTestDirty = false;
  10592. this._isDepthMaskDirty = false;
  10593. this._isDepthFuncDirty = false;
  10594. this._isCullFaceDirty = false;
  10595. this._isCullDirty = false;
  10596. this._isZOffsetDirty = false;
  10597. this._isFrontFaceDirty = false;
  10598. this.reset();
  10599. }
  10600. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10601. get: function () {
  10602. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10608. get: function () {
  10609. return this._zOffset;
  10610. },
  10611. set: function (value) {
  10612. if (this._zOffset === value) {
  10613. return;
  10614. }
  10615. this._zOffset = value;
  10616. this._isZOffsetDirty = true;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10622. get: function () {
  10623. return this._cullFace;
  10624. },
  10625. set: function (value) {
  10626. if (this._cullFace === value) {
  10627. return;
  10628. }
  10629. this._cullFace = value;
  10630. this._isCullFaceDirty = true;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10636. get: function () {
  10637. return this._cull;
  10638. },
  10639. set: function (value) {
  10640. if (this._cull === value) {
  10641. return;
  10642. }
  10643. this._cull = value;
  10644. this._isCullDirty = true;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10650. get: function () {
  10651. return this._depthFunc;
  10652. },
  10653. set: function (value) {
  10654. if (this._depthFunc === value) {
  10655. return;
  10656. }
  10657. this._depthFunc = value;
  10658. this._isDepthFuncDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10664. get: function () {
  10665. return this._depthMask;
  10666. },
  10667. set: function (value) {
  10668. if (this._depthMask === value) {
  10669. return;
  10670. }
  10671. this._depthMask = value;
  10672. this._isDepthMaskDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10678. get: function () {
  10679. return this._depthTest;
  10680. },
  10681. set: function (value) {
  10682. if (this._depthTest === value) {
  10683. return;
  10684. }
  10685. this._depthTest = value;
  10686. this._isDepthTestDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10692. get: function () {
  10693. return this._frontFace;
  10694. },
  10695. set: function (value) {
  10696. if (this._frontFace === value) {
  10697. return;
  10698. }
  10699. this._frontFace = value;
  10700. this._isFrontFaceDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. _DepthCullingState.prototype.reset = function () {
  10706. this._depthMask = true;
  10707. this._depthTest = true;
  10708. this._depthFunc = null;
  10709. this._cullFace = null;
  10710. this._cull = null;
  10711. this._zOffset = 0;
  10712. this._frontFace = null;
  10713. this._isDepthTestDirty = true;
  10714. this._isDepthMaskDirty = true;
  10715. this._isDepthFuncDirty = false;
  10716. this._isCullFaceDirty = false;
  10717. this._isCullDirty = false;
  10718. this._isZOffsetDirty = false;
  10719. this._isFrontFaceDirty = false;
  10720. };
  10721. _DepthCullingState.prototype.apply = function (gl) {
  10722. if (!this.isDirty) {
  10723. return;
  10724. }
  10725. // Cull
  10726. if (this._isCullDirty) {
  10727. if (this.cull) {
  10728. gl.enable(gl.CULL_FACE);
  10729. }
  10730. else {
  10731. gl.disable(gl.CULL_FACE);
  10732. }
  10733. this._isCullDirty = false;
  10734. }
  10735. // Cull face
  10736. if (this._isCullFaceDirty) {
  10737. gl.cullFace(this.cullFace);
  10738. this._isCullFaceDirty = false;
  10739. }
  10740. // Depth mask
  10741. if (this._isDepthMaskDirty) {
  10742. gl.depthMask(this.depthMask);
  10743. this._isDepthMaskDirty = false;
  10744. }
  10745. // Depth test
  10746. if (this._isDepthTestDirty) {
  10747. if (this.depthTest) {
  10748. gl.enable(gl.DEPTH_TEST);
  10749. }
  10750. else {
  10751. gl.disable(gl.DEPTH_TEST);
  10752. }
  10753. this._isDepthTestDirty = false;
  10754. }
  10755. // Depth func
  10756. if (this._isDepthFuncDirty) {
  10757. gl.depthFunc(this.depthFunc);
  10758. this._isDepthFuncDirty = false;
  10759. }
  10760. // zOffset
  10761. if (this._isZOffsetDirty) {
  10762. if (this.zOffset) {
  10763. gl.enable(gl.POLYGON_OFFSET_FILL);
  10764. gl.polygonOffset(this.zOffset, 0);
  10765. }
  10766. else {
  10767. gl.disable(gl.POLYGON_OFFSET_FILL);
  10768. }
  10769. this._isZOffsetDirty = false;
  10770. }
  10771. // Front face
  10772. if (this._isFrontFaceDirty) {
  10773. gl.frontFace(this.frontFace);
  10774. this._isFrontFaceDirty = false;
  10775. }
  10776. };
  10777. return _DepthCullingState;
  10778. }());
  10779. BABYLON._DepthCullingState = _DepthCullingState;
  10780. })(BABYLON || (BABYLON = {}));
  10781. //# sourceMappingURL=babylon.depthCullingState.js.map
  10782. var BABYLON;
  10783. (function (BABYLON) {
  10784. /**
  10785. * @hidden
  10786. **/
  10787. var _StencilState = /** @class */ (function () {
  10788. function _StencilState() {
  10789. this._isStencilTestDirty = false;
  10790. this._isStencilMaskDirty = false;
  10791. this._isStencilFuncDirty = false;
  10792. this._isStencilOpDirty = false;
  10793. this.reset();
  10794. }
  10795. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10796. get: function () {
  10797. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10803. get: function () {
  10804. return this._stencilFunc;
  10805. },
  10806. set: function (value) {
  10807. if (this._stencilFunc === value) {
  10808. return;
  10809. }
  10810. this._stencilFunc = value;
  10811. this._isStencilFuncDirty = true;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10817. get: function () {
  10818. return this._stencilFuncRef;
  10819. },
  10820. set: function (value) {
  10821. if (this._stencilFuncRef === value) {
  10822. return;
  10823. }
  10824. this._stencilFuncRef = value;
  10825. this._isStencilFuncDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10831. get: function () {
  10832. return this._stencilFuncMask;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilFuncMask === value) {
  10836. return;
  10837. }
  10838. this._stencilFuncMask = value;
  10839. this._isStencilFuncDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10845. get: function () {
  10846. return this._stencilOpStencilFail;
  10847. },
  10848. set: function (value) {
  10849. if (this._stencilOpStencilFail === value) {
  10850. return;
  10851. }
  10852. this._stencilOpStencilFail = value;
  10853. this._isStencilOpDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10859. get: function () {
  10860. return this._stencilOpDepthFail;
  10861. },
  10862. set: function (value) {
  10863. if (this._stencilOpDepthFail === value) {
  10864. return;
  10865. }
  10866. this._stencilOpDepthFail = value;
  10867. this._isStencilOpDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10873. get: function () {
  10874. return this._stencilOpStencilDepthPass;
  10875. },
  10876. set: function (value) {
  10877. if (this._stencilOpStencilDepthPass === value) {
  10878. return;
  10879. }
  10880. this._stencilOpStencilDepthPass = value;
  10881. this._isStencilOpDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10887. get: function () {
  10888. return this._stencilMask;
  10889. },
  10890. set: function (value) {
  10891. if (this._stencilMask === value) {
  10892. return;
  10893. }
  10894. this._stencilMask = value;
  10895. this._isStencilMaskDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10901. get: function () {
  10902. return this._stencilTest;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilTest === value) {
  10906. return;
  10907. }
  10908. this._stencilTest = value;
  10909. this._isStencilTestDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. _StencilState.prototype.reset = function () {
  10915. this._stencilTest = false;
  10916. this._stencilMask = 0xFF;
  10917. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10918. this._stencilFuncRef = 1;
  10919. this._stencilFuncMask = 0xFF;
  10920. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10921. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10922. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10923. this._isStencilTestDirty = true;
  10924. this._isStencilMaskDirty = true;
  10925. this._isStencilFuncDirty = true;
  10926. this._isStencilOpDirty = true;
  10927. };
  10928. _StencilState.prototype.apply = function (gl) {
  10929. if (!this.isDirty) {
  10930. return;
  10931. }
  10932. // Stencil test
  10933. if (this._isStencilTestDirty) {
  10934. if (this.stencilTest) {
  10935. gl.enable(gl.STENCIL_TEST);
  10936. }
  10937. else {
  10938. gl.disable(gl.STENCIL_TEST);
  10939. }
  10940. this._isStencilTestDirty = false;
  10941. }
  10942. // Stencil mask
  10943. if (this._isStencilMaskDirty) {
  10944. gl.stencilMask(this.stencilMask);
  10945. this._isStencilMaskDirty = false;
  10946. }
  10947. // Stencil func
  10948. if (this._isStencilFuncDirty) {
  10949. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10950. this._isStencilFuncDirty = false;
  10951. }
  10952. // Stencil op
  10953. if (this._isStencilOpDirty) {
  10954. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10955. this._isStencilOpDirty = false;
  10956. }
  10957. };
  10958. return _StencilState;
  10959. }());
  10960. BABYLON._StencilState = _StencilState;
  10961. })(BABYLON || (BABYLON = {}));
  10962. //# sourceMappingURL=babylon.stencilState.js.map
  10963. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10964. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10965. s = arguments[i];
  10966. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10967. t[p] = s[p];
  10968. }
  10969. return t;
  10970. };
  10971. var BABYLON;
  10972. (function (BABYLON) {
  10973. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10974. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10975. };
  10976. var compileRawShader = function (gl, source, type) {
  10977. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10978. gl.shaderSource(shader, source);
  10979. gl.compileShader(shader);
  10980. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10981. var log = gl.getShaderInfoLog(shader);
  10982. if (log) {
  10983. throw new Error(log);
  10984. }
  10985. }
  10986. if (!shader) {
  10987. throw new Error("Something went wrong while compile the shader.");
  10988. }
  10989. return shader;
  10990. };
  10991. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10992. var magFilter = gl.NEAREST;
  10993. var minFilter = gl.NEAREST;
  10994. switch (samplingMode) {
  10995. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10996. magFilter = gl.LINEAR;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11005. magFilter = gl.LINEAR;
  11006. if (generateMipMaps) {
  11007. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11008. }
  11009. else {
  11010. minFilter = gl.LINEAR;
  11011. }
  11012. break;
  11013. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11014. magFilter = gl.NEAREST;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11017. }
  11018. else {
  11019. minFilter = gl.NEAREST;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11023. magFilter = gl.NEAREST;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.NEAREST;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11041. magFilter = gl.NEAREST;
  11042. if (generateMipMaps) {
  11043. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11044. }
  11045. else {
  11046. minFilter = gl.LINEAR;
  11047. }
  11048. break;
  11049. case BABYLON.Texture.NEAREST_LINEAR:
  11050. magFilter = gl.NEAREST;
  11051. minFilter = gl.LINEAR;
  11052. break;
  11053. case BABYLON.Texture.NEAREST_NEAREST:
  11054. magFilter = gl.NEAREST;
  11055. minFilter = gl.NEAREST;
  11056. break;
  11057. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11058. magFilter = gl.LINEAR;
  11059. if (generateMipMaps) {
  11060. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11061. }
  11062. else {
  11063. minFilter = gl.NEAREST;
  11064. }
  11065. break;
  11066. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11067. magFilter = gl.LINEAR;
  11068. if (generateMipMaps) {
  11069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11070. }
  11071. else {
  11072. minFilter = gl.NEAREST;
  11073. }
  11074. break;
  11075. case BABYLON.Texture.LINEAR_LINEAR:
  11076. magFilter = gl.LINEAR;
  11077. minFilter = gl.LINEAR;
  11078. break;
  11079. case BABYLON.Texture.LINEAR_NEAREST:
  11080. magFilter = gl.LINEAR;
  11081. minFilter = gl.NEAREST;
  11082. break;
  11083. }
  11084. return {
  11085. min: minFilter,
  11086. mag: magFilter
  11087. };
  11088. };
  11089. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11090. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11091. var img;
  11092. var onload = function () {
  11093. loadedImages[index] = img;
  11094. loadedImages._internalCount++;
  11095. if (scene) {
  11096. scene._removePendingData(img);
  11097. }
  11098. if (loadedImages._internalCount === 6) {
  11099. onfinish(loadedImages);
  11100. }
  11101. };
  11102. var onerror = function (message, exception) {
  11103. if (scene) {
  11104. scene._removePendingData(img);
  11105. }
  11106. if (onErrorCallBack) {
  11107. onErrorCallBack(message, exception);
  11108. }
  11109. };
  11110. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11111. if (scene) {
  11112. scene._addPendingData(img);
  11113. }
  11114. };
  11115. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11116. if (onError === void 0) { onError = null; }
  11117. var loadedImages = [];
  11118. loadedImages._internalCount = 0;
  11119. for (var index = 0; index < 6; index++) {
  11120. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11121. }
  11122. };
  11123. var BufferPointer = /** @class */ (function () {
  11124. function BufferPointer() {
  11125. }
  11126. return BufferPointer;
  11127. }());
  11128. /**
  11129. * Interface for attribute information associated with buffer instanciation
  11130. */
  11131. var InstancingAttributeInfo = /** @class */ (function () {
  11132. function InstancingAttributeInfo() {
  11133. }
  11134. return InstancingAttributeInfo;
  11135. }());
  11136. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11137. /**
  11138. * Define options used to create a render target texture
  11139. */
  11140. var RenderTargetCreationOptions = /** @class */ (function () {
  11141. function RenderTargetCreationOptions() {
  11142. }
  11143. return RenderTargetCreationOptions;
  11144. }());
  11145. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11146. /**
  11147. * Define options used to create a depth texture
  11148. */
  11149. var DepthTextureCreationOptions = /** @class */ (function () {
  11150. function DepthTextureCreationOptions() {
  11151. }
  11152. return DepthTextureCreationOptions;
  11153. }());
  11154. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11155. /**
  11156. * Class used to describe the capabilities of the engine relatively to the current browser
  11157. */
  11158. var EngineCapabilities = /** @class */ (function () {
  11159. function EngineCapabilities() {
  11160. }
  11161. return EngineCapabilities;
  11162. }());
  11163. BABYLON.EngineCapabilities = EngineCapabilities;
  11164. /**
  11165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11166. */
  11167. var Engine = /** @class */ (function () {
  11168. /**
  11169. * Creates a new engine
  11170. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11171. * @param antialias defines enable antialiasing (default: false)
  11172. * @param options defines further options to be sent to the getContext() function
  11173. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11174. */
  11175. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11176. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11177. var _this = this;
  11178. // Public members
  11179. /**
  11180. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11181. */
  11182. this.forcePOTTextures = false;
  11183. /**
  11184. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11185. */
  11186. this.isFullscreen = false;
  11187. /**
  11188. * Gets a boolean indicating if the pointer is currently locked
  11189. */
  11190. this.isPointerLock = false;
  11191. /**
  11192. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11193. */
  11194. this.cullBackFaces = true;
  11195. /**
  11196. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11197. */
  11198. this.renderEvenInBackground = true;
  11199. /**
  11200. * Gets or sets a boolean indicating that cache can be kept between frames
  11201. */
  11202. this.preventCacheWipeBetweenFrames = false;
  11203. /**
  11204. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11205. **/
  11206. this.enableOfflineSupport = false;
  11207. /**
  11208. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11209. **/
  11210. this.disableManifestCheck = false;
  11211. /**
  11212. * Gets the list of created scenes
  11213. */
  11214. this.scenes = new Array();
  11215. /**
  11216. * Gets the list of created postprocesses
  11217. */
  11218. this.postProcesses = new Array();
  11219. // Observables
  11220. /**
  11221. * Observable event triggered each time the rendering canvas is resized
  11222. */
  11223. this.onResizeObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable event triggered each time the canvas loses focus
  11226. */
  11227. this.onCanvasBlurObservable = new BABYLON.Observable();
  11228. /**
  11229. * Observable event triggered each time the canvas gains focus
  11230. */
  11231. this.onCanvasFocusObservable = new BABYLON.Observable();
  11232. /**
  11233. * Observable event triggered each time the canvas receives pointerout event
  11234. */
  11235. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11236. /**
  11237. * Observable event triggered before each texture is initialized
  11238. */
  11239. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11240. //WebVR
  11241. this._vrDisplay = undefined;
  11242. this._vrSupported = false;
  11243. this._vrExclusivePointerMode = false;
  11244. // Uniform buffers list
  11245. /**
  11246. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11247. */
  11248. this.disableUniformBuffers = false;
  11249. /** @hidden */
  11250. this._uniformBuffers = new Array();
  11251. // Observables
  11252. /**
  11253. * Observable raised when the engine begins a new frame
  11254. */
  11255. this.onBeginFrameObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable raised when the engine ends the current frame
  11258. */
  11259. this.onEndFrameObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable raised when the engine is about to compile a shader
  11262. */
  11263. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable raised when the engine has jsut compiled a shader
  11266. */
  11267. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11268. this._windowIsBackground = false;
  11269. this._webGLVersion = 1.0;
  11270. /** @hidden */
  11271. this._badOS = false;
  11272. /** @hidden */
  11273. this._badDesktopOS = false;
  11274. /**
  11275. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11276. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11277. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11278. */
  11279. this.disableTextureBindingOptimization = false;
  11280. /**
  11281. * Observable signaled when VR display mode changes
  11282. */
  11283. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable signaled when VR request present is complete
  11286. */
  11287. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11288. /**
  11289. * Observable signaled when VR request present starts
  11290. */
  11291. this.onVRRequestPresentStart = new BABYLON.Observable();
  11292. this._colorWrite = true;
  11293. /** @hidden */
  11294. this._drawCalls = new BABYLON.PerfCounter();
  11295. /** @hidden */
  11296. this._textureCollisions = new BABYLON.PerfCounter();
  11297. this._renderingQueueLaunched = false;
  11298. this._activeRenderLoops = new Array();
  11299. // Deterministic lockstepMaxSteps
  11300. this._deterministicLockstep = false;
  11301. this._lockstepMaxSteps = 4;
  11302. // Lost context
  11303. /**
  11304. * Observable signaled when a context lost event is raised
  11305. */
  11306. this.onContextLostObservable = new BABYLON.Observable();
  11307. /**
  11308. * Observable signaled when a context restored event is raised
  11309. */
  11310. this.onContextRestoredObservable = new BABYLON.Observable();
  11311. this._contextWasLost = false;
  11312. this._doNotHandleContextLost = false;
  11313. // FPS
  11314. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11315. this._fps = 60;
  11316. this._deltaTime = 0;
  11317. /**
  11318. * Turn this value on if you want to pause FPS computation when in background
  11319. */
  11320. this.disablePerformanceMonitorInBackground = false;
  11321. // States
  11322. /** @hidden */
  11323. this._depthCullingState = new BABYLON._DepthCullingState();
  11324. /** @hidden */
  11325. this._stencilState = new BABYLON._StencilState();
  11326. /** @hidden */
  11327. this._alphaState = new BABYLON._AlphaState();
  11328. /** @hidden */
  11329. this._alphaMode = Engine.ALPHA_DISABLE;
  11330. // Cache
  11331. this._internalTexturesCache = new Array();
  11332. /** @hidden */
  11333. this._activeChannel = 0;
  11334. this._currentTextureChannel = -1;
  11335. /** @hidden */
  11336. this._boundTexturesCache = {};
  11337. this._compiledEffects = {};
  11338. this._vertexAttribArraysEnabled = [];
  11339. this._uintIndicesCurrentlySet = false;
  11340. this._currentBoundBuffer = new Array();
  11341. this._currentBufferPointers = new Array();
  11342. this._currentInstanceLocations = new Array();
  11343. this._currentInstanceBuffers = new Array();
  11344. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11345. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11346. this._vaoRecordInProgress = false;
  11347. this._mustWipeVertexAttributes = false;
  11348. this._nextFreeTextureSlots = new Array();
  11349. this._maxSimultaneousTextures = 0;
  11350. this._activeRequests = new Array();
  11351. // Hardware supported Compressed Textures
  11352. this._texturesSupported = new Array();
  11353. /**
  11354. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11355. */
  11356. this.premultipliedAlpha = true;
  11357. this._onVRFullScreenTriggered = function () {
  11358. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11359. //get the old size before we change
  11360. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11361. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11362. //get the width and height, change the render size
  11363. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11364. _this.setHardwareScalingLevel(1);
  11365. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11366. }
  11367. else {
  11368. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11369. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11370. }
  11371. };
  11372. this._boundUniforms = {};
  11373. // Register promises
  11374. BABYLON.PromisePolyfill.Apply();
  11375. var canvas = null;
  11376. Engine.Instances.push(this);
  11377. if (!canvasOrContext) {
  11378. return;
  11379. }
  11380. options = options || {};
  11381. if (canvasOrContext.getContext) {
  11382. canvas = canvasOrContext;
  11383. this._renderingCanvas = canvas;
  11384. if (antialias != null) {
  11385. options.antialias = antialias;
  11386. }
  11387. if (options.deterministicLockstep === undefined) {
  11388. options.deterministicLockstep = false;
  11389. }
  11390. if (options.lockstepMaxSteps === undefined) {
  11391. options.lockstepMaxSteps = 4;
  11392. }
  11393. if (options.preserveDrawingBuffer === undefined) {
  11394. options.preserveDrawingBuffer = false;
  11395. }
  11396. if (options.audioEngine === undefined) {
  11397. options.audioEngine = true;
  11398. }
  11399. if (options.stencil === undefined) {
  11400. options.stencil = true;
  11401. }
  11402. if (options.premultipliedAlpha === false) {
  11403. this.premultipliedAlpha = false;
  11404. }
  11405. this._deterministicLockstep = options.deterministicLockstep;
  11406. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11407. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11408. // Exceptions
  11409. if (navigator && navigator.userAgent) {
  11410. var ua = navigator.userAgent;
  11411. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11412. var exception = _a[_i];
  11413. var key = exception.key;
  11414. var targets = exception.targets;
  11415. if (ua.indexOf(key) > -1) {
  11416. if (exception.capture && exception.captureConstraint) {
  11417. var capture = exception.capture;
  11418. var constraint = exception.captureConstraint;
  11419. var regex = new RegExp(capture);
  11420. var matches = regex.exec(ua);
  11421. if (matches && matches.length > 0) {
  11422. var capturedValue = parseInt(matches[matches.length - 1]);
  11423. if (capturedValue >= constraint) {
  11424. continue;
  11425. }
  11426. }
  11427. }
  11428. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11429. var target = targets_1[_b];
  11430. switch (target) {
  11431. case "uniformBuffer":
  11432. this.disableUniformBuffers = true;
  11433. break;
  11434. case "textureBindingOptimization":
  11435. this.disableTextureBindingOptimization = true;
  11436. break;
  11437. }
  11438. }
  11439. }
  11440. }
  11441. }
  11442. // GL
  11443. if (!options.disableWebGL2Support) {
  11444. try {
  11445. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11446. if (this._gl) {
  11447. this._webGLVersion = 2.0;
  11448. }
  11449. }
  11450. catch (e) {
  11451. // Do nothing
  11452. }
  11453. }
  11454. if (!this._gl) {
  11455. if (!canvas) {
  11456. throw new Error("The provided canvas is null or undefined.");
  11457. }
  11458. try {
  11459. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11460. }
  11461. catch (e) {
  11462. throw new Error("WebGL not supported");
  11463. }
  11464. }
  11465. if (!this._gl) {
  11466. throw new Error("WebGL not supported");
  11467. }
  11468. this._onCanvasFocus = function () {
  11469. _this.onCanvasFocusObservable.notifyObservers(_this);
  11470. };
  11471. this._onCanvasBlur = function () {
  11472. _this.onCanvasBlurObservable.notifyObservers(_this);
  11473. };
  11474. canvas.addEventListener("focus", this._onCanvasFocus);
  11475. canvas.addEventListener("blur", this._onCanvasBlur);
  11476. this._onBlur = function () {
  11477. if (_this.disablePerformanceMonitorInBackground) {
  11478. _this._performanceMonitor.disable();
  11479. }
  11480. _this._windowIsBackground = true;
  11481. };
  11482. this._onFocus = function () {
  11483. if (_this.disablePerformanceMonitorInBackground) {
  11484. _this._performanceMonitor.enable();
  11485. }
  11486. _this._windowIsBackground = false;
  11487. };
  11488. this._onCanvasPointerOut = function (ev) {
  11489. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11490. };
  11491. window.addEventListener("blur", this._onBlur);
  11492. window.addEventListener("focus", this._onFocus);
  11493. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11494. // Context lost
  11495. if (!this._doNotHandleContextLost) {
  11496. this._onContextLost = function (evt) {
  11497. evt.preventDefault();
  11498. _this._contextWasLost = true;
  11499. BABYLON.Tools.Warn("WebGL context lost.");
  11500. _this.onContextLostObservable.notifyObservers(_this);
  11501. };
  11502. this._onContextRestored = function (evt) {
  11503. // Adding a timeout to avoid race condition at browser level
  11504. setTimeout(function () {
  11505. // Rebuild gl context
  11506. _this._initGLContext();
  11507. // Rebuild effects
  11508. _this._rebuildEffects();
  11509. // Rebuild textures
  11510. _this._rebuildInternalTextures();
  11511. // Rebuild buffers
  11512. _this._rebuildBuffers();
  11513. // Cache
  11514. _this.wipeCaches(true);
  11515. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11516. _this.onContextRestoredObservable.notifyObservers(_this);
  11517. _this._contextWasLost = false;
  11518. }, 0);
  11519. };
  11520. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11521. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11522. }
  11523. }
  11524. else {
  11525. this._gl = canvasOrContext;
  11526. this._renderingCanvas = this._gl.canvas;
  11527. if (this._gl.renderbufferStorageMultisample) {
  11528. this._webGLVersion = 2.0;
  11529. }
  11530. options.stencil = this._gl.getContextAttributes().stencil;
  11531. }
  11532. // Viewport
  11533. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11534. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11535. this.resize();
  11536. this._isStencilEnable = options.stencil ? true : false;
  11537. this._initGLContext();
  11538. if (canvas) {
  11539. // Fullscreen
  11540. this._onFullscreenChange = function () {
  11541. if (document.fullscreen !== undefined) {
  11542. _this.isFullscreen = document.fullscreen;
  11543. }
  11544. else if (document.mozFullScreen !== undefined) {
  11545. _this.isFullscreen = document.mozFullScreen;
  11546. }
  11547. else if (document.webkitIsFullScreen !== undefined) {
  11548. _this.isFullscreen = document.webkitIsFullScreen;
  11549. }
  11550. else if (document.msIsFullScreen !== undefined) {
  11551. _this.isFullscreen = document.msIsFullScreen;
  11552. }
  11553. // Pointer lock
  11554. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11555. canvas.requestPointerLock = canvas.requestPointerLock ||
  11556. canvas.msRequestPointerLock ||
  11557. canvas.mozRequestPointerLock ||
  11558. canvas.webkitRequestPointerLock;
  11559. if (canvas.requestPointerLock) {
  11560. canvas.requestPointerLock();
  11561. }
  11562. }
  11563. };
  11564. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11565. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11566. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11567. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11568. // Pointer lock
  11569. this._onPointerLockChange = function () {
  11570. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11571. document.webkitPointerLockElement === canvas ||
  11572. document.msPointerLockElement === canvas ||
  11573. document.pointerLockElement === canvas);
  11574. };
  11575. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11576. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11577. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11578. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11579. this._onVRDisplayPointerRestricted = function () {
  11580. if (canvas) {
  11581. canvas.requestPointerLock();
  11582. }
  11583. };
  11584. this._onVRDisplayPointerUnrestricted = function () {
  11585. document.exitPointerLock();
  11586. };
  11587. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11588. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11589. }
  11590. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11591. Engine.audioEngine = new BABYLON.AudioEngine();
  11592. }
  11593. // Prepare buffer pointers
  11594. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11595. this._currentBufferPointers[i] = new BufferPointer();
  11596. }
  11597. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11598. // Load WebVR Devices
  11599. if (options.autoEnableWebVR) {
  11600. this.initWebVR();
  11601. }
  11602. // Detect if we are running on a faulty buggy OS.
  11603. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11604. // Detect if we are running on a faulty buggy desktop OS.
  11605. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11606. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11607. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11608. }
  11609. Object.defineProperty(Engine, "LastCreatedEngine", {
  11610. /**
  11611. * Gets the latest created engine
  11612. */
  11613. get: function () {
  11614. if (Engine.Instances.length === 0) {
  11615. return null;
  11616. }
  11617. return Engine.Instances[Engine.Instances.length - 1];
  11618. },
  11619. enumerable: true,
  11620. configurable: true
  11621. });
  11622. Object.defineProperty(Engine, "LastCreatedScene", {
  11623. /**
  11624. * Gets the latest created scene
  11625. */
  11626. get: function () {
  11627. var lastCreatedEngine = Engine.LastCreatedEngine;
  11628. if (!lastCreatedEngine) {
  11629. return null;
  11630. }
  11631. if (lastCreatedEngine.scenes.length === 0) {
  11632. return null;
  11633. }
  11634. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. /**
  11640. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11641. * @param flag defines which part of the materials must be marked as dirty
  11642. * @param predicate defines a predicate used to filter which materials should be affected
  11643. */
  11644. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11645. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11646. var engine = Engine.Instances[engineIndex];
  11647. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11648. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11649. }
  11650. }
  11651. };
  11652. Object.defineProperty(Engine, "NEVER", {
  11653. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11654. get: function () {
  11655. return Engine._NEVER;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "ALWAYS", {
  11661. /** 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 */
  11662. get: function () {
  11663. return Engine._ALWAYS;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "LESS", {
  11669. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11670. get: function () {
  11671. return Engine._LESS;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "EQUAL", {
  11677. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11678. get: function () {
  11679. return Engine._EQUAL;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "LEQUAL", {
  11685. /** 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 */
  11686. get: function () {
  11687. return Engine._LEQUAL;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "GREATER", {
  11693. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11694. get: function () {
  11695. return Engine._GREATER;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "GEQUAL", {
  11701. /** 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 */
  11702. get: function () {
  11703. return Engine._GEQUAL;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "NOTEQUAL", {
  11709. /** 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 */
  11710. get: function () {
  11711. return Engine._NOTEQUAL;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "KEEP", {
  11717. /** Passed to stencilOperation to specify that stencil value must be kept */
  11718. get: function () {
  11719. return Engine._KEEP;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "REPLACE", {
  11725. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11726. get: function () {
  11727. return Engine._REPLACE;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "INCR", {
  11733. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11734. get: function () {
  11735. return Engine._INCR;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "DECR", {
  11741. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11742. get: function () {
  11743. return Engine._DECR;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "INVERT", {
  11749. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11750. get: function () {
  11751. return Engine._INVERT;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "INCR_WRAP", {
  11757. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11758. get: function () {
  11759. return Engine._INCR_WRAP;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "DECR_WRAP", {
  11765. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11766. get: function () {
  11767. return Engine._DECR_WRAP;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11773. // Alpha
  11774. /** Defines that alpha blending is disabled */
  11775. get: function () {
  11776. return Engine._ALPHA_DISABLE;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11782. /** Defines that alpha blending to SRC + DEST */
  11783. get: function () {
  11784. return Engine._ALPHA_ONEONE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "ALPHA_ADD", {
  11790. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11791. get: function () {
  11792. return Engine._ALPHA_ADD;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11798. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11799. get: function () {
  11800. return Engine._ALPHA_COMBINE;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11806. /** Defines that alpha blending to DEST - SRC * DEST */
  11807. get: function () {
  11808. return Engine._ALPHA_SUBTRACT;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11814. /** Defines that alpha blending to SRC * DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_MULTIPLY;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11822. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11823. get: function () {
  11824. return Engine._ALPHA_MAXIMIZED;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11830. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11831. get: function () {
  11832. return Engine._ALPHA_PREMULTIPLIED;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11838. /**
  11839. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11840. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11841. */
  11842. get: function () {
  11843. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11849. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11850. get: function () {
  11851. return Engine._ALPHA_INTERPOLATE;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11857. /**
  11858. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11859. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11860. */
  11861. get: function () {
  11862. return Engine._ALPHA_SCREENMODE;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11868. // Delays
  11869. /** Defines that the ressource is not delayed*/
  11870. get: function () {
  11871. return Engine._DELAYLOADSTATE_NONE;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11877. /** Defines that the ressource was successfully delay loaded */
  11878. get: function () {
  11879. return Engine._DELAYLOADSTATE_LOADED;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11885. /** Defines that the ressource is currently delay loading */
  11886. get: function () {
  11887. return Engine._DELAYLOADSTATE_LOADING;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11893. /** Defines that the ressource is delayed and has not started loading */
  11894. get: function () {
  11895. return Engine._DELAYLOADSTATE_NOTLOADED;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11901. /** ALPHA */
  11902. get: function () {
  11903. return Engine._TEXTUREFORMAT_ALPHA;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11909. /** LUMINANCE */
  11910. get: function () {
  11911. return Engine._TEXTUREFORMAT_LUMINANCE;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11917. /**
  11918. * R
  11919. */
  11920. get: function () {
  11921. return Engine._TEXTUREFORMAT_R;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11927. /**
  11928. * RG
  11929. */
  11930. get: function () {
  11931. return Engine._TEXTUREFORMAT_RG;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11937. /** LUMINANCE_ALPHA */
  11938. get: function () {
  11939. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11945. /** RGB */
  11946. get: function () {
  11947. return Engine._TEXTUREFORMAT_RGB;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11953. /** RGBA */
  11954. get: function () {
  11955. return Engine._TEXTUREFORMAT_RGBA;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11961. /** UNSIGNED_INT */
  11962. get: function () {
  11963. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11969. /** FLOAT */
  11970. get: function () {
  11971. return Engine._TEXTURETYPE_FLOAT;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11977. /** HALF_FLOAT */
  11978. get: function () {
  11979. return Engine._TEXTURETYPE_HALF_FLOAT;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11985. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11986. get: function () {
  11987. return Engine._SCALEMODE_FLOOR;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11993. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11994. get: function () {
  11995. return Engine._SCALEMODE_NEAREST;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12001. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12002. get: function () {
  12003. return Engine._SCALEMODE_CEILING;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine, "Version", {
  12009. /**
  12010. * Returns the current version of the framework
  12011. */
  12012. get: function () {
  12013. return "3.3.0-alpha.5";
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12019. /**
  12020. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12021. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12022. */
  12023. get: function () {
  12024. return this._vrExclusivePointerMode;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12030. /**
  12031. * Gets a boolean indicating that the engine supports uniform buffers
  12032. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12033. */
  12034. get: function () {
  12035. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12041. /**
  12042. * Gets a boolean indicating that only power of 2 textures are supported
  12043. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12044. */
  12045. get: function () {
  12046. return this._webGLVersion < 2 || this.forcePOTTextures;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12052. /**
  12053. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12054. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12055. */
  12056. get: function () {
  12057. return this._doNotHandleContextLost;
  12058. },
  12059. set: function (value) {
  12060. this._doNotHandleContextLost = value;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12066. /**
  12067. * Gets the performance monitor attached to this engine
  12068. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12069. */
  12070. get: function () {
  12071. return this._performanceMonitor;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12077. /**
  12078. * Gets the list of texture formats supported
  12079. */
  12080. get: function () {
  12081. return this._texturesSupported;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12087. /**
  12088. * Gets the list of texture formats in use
  12089. */
  12090. get: function () {
  12091. return this._textureFormatInUse;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "currentViewport", {
  12097. /**
  12098. * Gets the current viewport
  12099. */
  12100. get: function () {
  12101. return this._cachedViewport;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12107. /**
  12108. * Gets the default empty texture
  12109. */
  12110. get: function () {
  12111. if (!this._emptyTexture) {
  12112. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12113. }
  12114. return this._emptyTexture;
  12115. },
  12116. enumerable: true,
  12117. configurable: true
  12118. });
  12119. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12120. /**
  12121. * Gets the default empty 3D texture
  12122. */
  12123. get: function () {
  12124. if (!this._emptyTexture3D) {
  12125. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12126. }
  12127. return this._emptyTexture3D;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12133. /**
  12134. * Gets the default empty cube texture
  12135. */
  12136. get: function () {
  12137. if (!this._emptyCubeTexture) {
  12138. var faceData = new Uint8Array(4);
  12139. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12140. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12141. }
  12142. return this._emptyCubeTexture;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Engine.prototype._rebuildInternalTextures = function () {
  12148. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12149. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12150. var internalTexture = currentState_1[_i];
  12151. internalTexture._rebuild();
  12152. }
  12153. };
  12154. Engine.prototype._rebuildEffects = function () {
  12155. for (var key in this._compiledEffects) {
  12156. var effect = this._compiledEffects[key];
  12157. effect._prepareEffect();
  12158. }
  12159. BABYLON.Effect.ResetCache();
  12160. };
  12161. Engine.prototype._rebuildBuffers = function () {
  12162. // Index / Vertex
  12163. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12164. var scene = _a[_i];
  12165. scene.resetCachedMaterial();
  12166. scene._rebuildGeometries();
  12167. scene._rebuildTextures();
  12168. }
  12169. // Uniforms
  12170. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12171. var uniformBuffer = _c[_b];
  12172. uniformBuffer._rebuild();
  12173. }
  12174. };
  12175. Engine.prototype._initGLContext = function () {
  12176. // Caps
  12177. this._caps = new EngineCapabilities();
  12178. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12179. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12180. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12181. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12182. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12183. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12184. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12185. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12186. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12187. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12188. // Infos
  12189. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12190. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12191. if (rendererInfo != null) {
  12192. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12193. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12194. }
  12195. if (!this._glVendor) {
  12196. this._glVendor = "Unknown vendor";
  12197. }
  12198. if (!this._glRenderer) {
  12199. this._glRenderer = "Unknown renderer";
  12200. }
  12201. // Constants
  12202. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12203. if (this._gl.RGBA16F !== 0x881A) {
  12204. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12205. }
  12206. if (this._gl.RGBA32F !== 0x8814) {
  12207. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12208. }
  12209. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12210. this._gl.DEPTH24_STENCIL8 = 35056;
  12211. }
  12212. // Extensions
  12213. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12214. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12215. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12216. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12217. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12218. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12219. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12220. 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');
  12221. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12222. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12223. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12224. this._caps.highPrecisionShaderSupported = true;
  12225. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12226. if (this._caps.timerQuery) {
  12227. if (this._webGLVersion === 1) {
  12228. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12229. }
  12230. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12231. }
  12232. // Checks if some of the format renders first to allow the use of webgl inspector.
  12233. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12234. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12235. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12236. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12237. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12238. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12239. if (this._webGLVersion > 1) {
  12240. this._gl.HALF_FLOAT_OES = 0x140B;
  12241. }
  12242. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12243. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12244. // Draw buffers
  12245. if (this._webGLVersion > 1) {
  12246. this._caps.drawBuffersExtension = true;
  12247. }
  12248. else {
  12249. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12250. if (drawBuffersExtension !== null) {
  12251. this._caps.drawBuffersExtension = true;
  12252. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12253. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12254. for (var i = 0; i < 16; i++) {
  12255. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12256. }
  12257. }
  12258. else {
  12259. this._caps.drawBuffersExtension = false;
  12260. }
  12261. }
  12262. // Depth Texture
  12263. if (this._webGLVersion > 1) {
  12264. this._caps.depthTextureExtension = true;
  12265. }
  12266. else {
  12267. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12268. if (depthTextureExtension != null) {
  12269. this._caps.depthTextureExtension = true;
  12270. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12271. }
  12272. }
  12273. // Vertex array object
  12274. if (this._webGLVersion > 1) {
  12275. this._caps.vertexArrayObject = true;
  12276. }
  12277. else {
  12278. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12279. if (vertexArrayObjectExtension != null) {
  12280. this._caps.vertexArrayObject = true;
  12281. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12282. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12283. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12284. }
  12285. else {
  12286. this._caps.vertexArrayObject = false;
  12287. }
  12288. }
  12289. // Instances count
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.instancedArrays = true;
  12292. }
  12293. else {
  12294. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12295. if (instanceExtension != null) {
  12296. this._caps.instancedArrays = true;
  12297. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12298. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12299. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12300. }
  12301. else {
  12302. this._caps.instancedArrays = false;
  12303. }
  12304. }
  12305. // Intelligently add supported compressed formats in order to check for.
  12306. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12307. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12308. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12309. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12310. if (this._caps.astc)
  12311. this.texturesSupported.push('-astc.ktx');
  12312. if (this._caps.s3tc)
  12313. this.texturesSupported.push('-dxt.ktx');
  12314. if (this._caps.pvrtc)
  12315. this.texturesSupported.push('-pvrtc.ktx');
  12316. if (this._caps.etc2)
  12317. this.texturesSupported.push('-etc2.ktx');
  12318. if (this._caps.etc1)
  12319. this.texturesSupported.push('-etc1.ktx');
  12320. if (this._gl.getShaderPrecisionFormat) {
  12321. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12322. if (highp) {
  12323. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12324. }
  12325. }
  12326. // Depth buffer
  12327. this.setDepthBuffer(true);
  12328. this.setDepthFunctionToLessOrEqual();
  12329. this.setDepthWrite(true);
  12330. // Texture maps
  12331. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12332. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12333. this._nextFreeTextureSlots.push(slot);
  12334. }
  12335. };
  12336. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12337. /**
  12338. * Gets version of the current webGL context
  12339. */
  12340. get: function () {
  12341. return this._webGLVersion;
  12342. },
  12343. enumerable: true,
  12344. configurable: true
  12345. });
  12346. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12347. /**
  12348. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12349. */
  12350. get: function () {
  12351. return this._isStencilEnable;
  12352. },
  12353. enumerable: true,
  12354. configurable: true
  12355. });
  12356. Engine.prototype._prepareWorkingCanvas = function () {
  12357. if (this._workingCanvas) {
  12358. return;
  12359. }
  12360. this._workingCanvas = document.createElement("canvas");
  12361. var context = this._workingCanvas.getContext("2d");
  12362. if (context) {
  12363. this._workingContext = context;
  12364. }
  12365. };
  12366. /**
  12367. * Reset the texture cache to empty state
  12368. */
  12369. Engine.prototype.resetTextureCache = function () {
  12370. for (var key in this._boundTexturesCache) {
  12371. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12372. continue;
  12373. }
  12374. var boundTexture = this._boundTexturesCache[key];
  12375. if (boundTexture) {
  12376. this._removeDesignatedSlot(boundTexture);
  12377. }
  12378. this._boundTexturesCache[key] = null;
  12379. }
  12380. if (!this.disableTextureBindingOptimization) {
  12381. this._nextFreeTextureSlots = [];
  12382. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12383. this._nextFreeTextureSlots.push(slot);
  12384. }
  12385. }
  12386. this._currentTextureChannel = -1;
  12387. };
  12388. /**
  12389. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12390. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12391. * @returns true if engine is in deterministic lock step mode
  12392. */
  12393. Engine.prototype.isDeterministicLockStep = function () {
  12394. return this._deterministicLockstep;
  12395. };
  12396. /**
  12397. * Gets the max steps when engine is running in deterministic lock step
  12398. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12399. * @returns the max steps
  12400. */
  12401. Engine.prototype.getLockstepMaxSteps = function () {
  12402. return this._lockstepMaxSteps;
  12403. };
  12404. /**
  12405. * Gets an object containing information about the current webGL context
  12406. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12407. */
  12408. Engine.prototype.getGlInfo = function () {
  12409. return {
  12410. vendor: this._glVendor,
  12411. renderer: this._glRenderer,
  12412. version: this._glVersion
  12413. };
  12414. };
  12415. /**
  12416. * Gets current aspect ratio
  12417. * @param camera defines the camera to use to get the aspect ratio
  12418. * @param useScreen defines if screen size must be used (or the current render target if any)
  12419. * @returns a number defining the aspect ratio
  12420. */
  12421. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12422. if (useScreen === void 0) { useScreen = false; }
  12423. var viewport = camera.viewport;
  12424. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12425. };
  12426. /**
  12427. * Gets current screen aspect ratio
  12428. * @returns a number defining the aspect ratio
  12429. */
  12430. Engine.prototype.getScreenAspectRatio = function () {
  12431. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12432. };
  12433. /**
  12434. * Gets the current render width
  12435. * @param useScreen defines if screen size must be used (or the current render target if any)
  12436. * @returns a number defining the current render width
  12437. */
  12438. Engine.prototype.getRenderWidth = function (useScreen) {
  12439. if (useScreen === void 0) { useScreen = false; }
  12440. if (!useScreen && this._currentRenderTarget) {
  12441. return this._currentRenderTarget.width;
  12442. }
  12443. return this._gl.drawingBufferWidth;
  12444. };
  12445. /**
  12446. * Gets the current render height
  12447. * @param useScreen defines if screen size must be used (or the current render target if any)
  12448. * @returns a number defining the current render height
  12449. */
  12450. Engine.prototype.getRenderHeight = function (useScreen) {
  12451. if (useScreen === void 0) { useScreen = false; }
  12452. if (!useScreen && this._currentRenderTarget) {
  12453. return this._currentRenderTarget.height;
  12454. }
  12455. return this._gl.drawingBufferHeight;
  12456. };
  12457. /**
  12458. * Gets the HTML canvas attached with the current webGL context
  12459. * @returns a HTML canvas
  12460. */
  12461. Engine.prototype.getRenderingCanvas = function () {
  12462. return this._renderingCanvas;
  12463. };
  12464. /**
  12465. * Gets the client rect of the HTML canvas attached with the current webGL context
  12466. * @returns a client rectanglee
  12467. */
  12468. Engine.prototype.getRenderingCanvasClientRect = function () {
  12469. if (!this._renderingCanvas) {
  12470. return null;
  12471. }
  12472. return this._renderingCanvas.getBoundingClientRect();
  12473. };
  12474. /**
  12475. * Defines the hardware scaling level.
  12476. * By default the hardware scaling level is computed from the window device ratio.
  12477. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12478. * @param level defines the level to use
  12479. */
  12480. Engine.prototype.setHardwareScalingLevel = function (level) {
  12481. this._hardwareScalingLevel = level;
  12482. this.resize();
  12483. };
  12484. /**
  12485. * Gets the current hardware scaling level.
  12486. * By default the hardware scaling level is computed from the window device ratio.
  12487. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12488. * @returns a number indicating the current hardware scaling level
  12489. */
  12490. Engine.prototype.getHardwareScalingLevel = function () {
  12491. return this._hardwareScalingLevel;
  12492. };
  12493. /**
  12494. * Gets the list of loaded textures
  12495. * @returns an array containing all loaded textures
  12496. */
  12497. Engine.prototype.getLoadedTexturesCache = function () {
  12498. return this._internalTexturesCache;
  12499. };
  12500. /**
  12501. * Gets the object containing all engine capabilities
  12502. * @returns the EngineCapabilities object
  12503. */
  12504. Engine.prototype.getCaps = function () {
  12505. return this._caps;
  12506. };
  12507. Object.defineProperty(Engine.prototype, "drawCalls", {
  12508. /** @hidden */
  12509. get: function () {
  12510. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12511. return 0;
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12517. /** @hidden */
  12518. get: function () {
  12519. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12520. return null;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. /**
  12526. * Gets the current depth function
  12527. * @returns a number defining the depth function
  12528. */
  12529. Engine.prototype.getDepthFunction = function () {
  12530. return this._depthCullingState.depthFunc;
  12531. };
  12532. /**
  12533. * Sets the current depth function
  12534. * @param depthFunc defines the function to use
  12535. */
  12536. Engine.prototype.setDepthFunction = function (depthFunc) {
  12537. this._depthCullingState.depthFunc = depthFunc;
  12538. };
  12539. /**
  12540. * Sets the current depth function to GREATER
  12541. */
  12542. Engine.prototype.setDepthFunctionToGreater = function () {
  12543. this._depthCullingState.depthFunc = this._gl.GREATER;
  12544. };
  12545. /**
  12546. * Sets the current depth function to GEQUAL
  12547. */
  12548. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12549. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12550. };
  12551. /**
  12552. * Sets the current depth function to LESS
  12553. */
  12554. Engine.prototype.setDepthFunctionToLess = function () {
  12555. this._depthCullingState.depthFunc = this._gl.LESS;
  12556. };
  12557. /**
  12558. * Sets the current depth function to LEQUAL
  12559. */
  12560. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12561. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12562. };
  12563. /**
  12564. * Gets a boolean indicating if stencil buffer is enabled
  12565. * @returns the current stencil buffer state
  12566. */
  12567. Engine.prototype.getStencilBuffer = function () {
  12568. return this._stencilState.stencilTest;
  12569. };
  12570. /**
  12571. * Enable or disable the stencil buffer
  12572. * @param enable defines if the stencil buffer must be enabled or disabled
  12573. */
  12574. Engine.prototype.setStencilBuffer = function (enable) {
  12575. this._stencilState.stencilTest = enable;
  12576. };
  12577. /**
  12578. * Gets the current stencil mask
  12579. * @returns a number defining the new stencil mask to use
  12580. */
  12581. Engine.prototype.getStencilMask = function () {
  12582. return this._stencilState.stencilMask;
  12583. };
  12584. /**
  12585. * Sets the current stencil mask
  12586. * @param mask defines the new stencil mask to use
  12587. */
  12588. Engine.prototype.setStencilMask = function (mask) {
  12589. this._stencilState.stencilMask = mask;
  12590. };
  12591. /**
  12592. * Gets the current stencil function
  12593. * @returns a number defining the stencil function to use
  12594. */
  12595. Engine.prototype.getStencilFunction = function () {
  12596. return this._stencilState.stencilFunc;
  12597. };
  12598. /**
  12599. * Gets the current stencil reference value
  12600. * @returns a number defining the stencil reference value to use
  12601. */
  12602. Engine.prototype.getStencilFunctionReference = function () {
  12603. return this._stencilState.stencilFuncRef;
  12604. };
  12605. /**
  12606. * Gets the current stencil mask
  12607. * @returns a number defining the stencil mask to use
  12608. */
  12609. Engine.prototype.getStencilFunctionMask = function () {
  12610. return this._stencilState.stencilFuncMask;
  12611. };
  12612. /**
  12613. * Sets the current stencil function
  12614. * @param stencilFunc defines the new stencil function to use
  12615. */
  12616. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12617. this._stencilState.stencilFunc = stencilFunc;
  12618. };
  12619. /**
  12620. * Sets the current stencil reference
  12621. * @param reference defines the new stencil reference to use
  12622. */
  12623. Engine.prototype.setStencilFunctionReference = function (reference) {
  12624. this._stencilState.stencilFuncRef = reference;
  12625. };
  12626. /**
  12627. * Sets the current stencil mask
  12628. * @param mask defines the new stencil mask to use
  12629. */
  12630. Engine.prototype.setStencilFunctionMask = function (mask) {
  12631. this._stencilState.stencilFuncMask = mask;
  12632. };
  12633. /**
  12634. * Gets the current stencil operation when stencil fails
  12635. * @returns a number defining stencil operation to use when stencil fails
  12636. */
  12637. Engine.prototype.getStencilOperationFail = function () {
  12638. return this._stencilState.stencilOpStencilFail;
  12639. };
  12640. /**
  12641. * Gets the current stencil operation when depth fails
  12642. * @returns a number defining stencil operation to use when depth fails
  12643. */
  12644. Engine.prototype.getStencilOperationDepthFail = function () {
  12645. return this._stencilState.stencilOpDepthFail;
  12646. };
  12647. /**
  12648. * Gets the current stencil operation when stencil passes
  12649. * @returns a number defining stencil operation to use when stencil passes
  12650. */
  12651. Engine.prototype.getStencilOperationPass = function () {
  12652. return this._stencilState.stencilOpStencilDepthPass;
  12653. };
  12654. /**
  12655. * Sets the stencil operation to use when stencil fails
  12656. * @param operation defines the stencil operation to use when stencil fails
  12657. */
  12658. Engine.prototype.setStencilOperationFail = function (operation) {
  12659. this._stencilState.stencilOpStencilFail = operation;
  12660. };
  12661. /**
  12662. * Sets the stencil operation to use when depth fails
  12663. * @param operation defines the stencil operation to use when depth fails
  12664. */
  12665. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12666. this._stencilState.stencilOpDepthFail = operation;
  12667. };
  12668. /**
  12669. * Sets the stencil operation to use when stencil passes
  12670. * @param operation defines the stencil operation to use when stencil passes
  12671. */
  12672. Engine.prototype.setStencilOperationPass = function (operation) {
  12673. this._stencilState.stencilOpStencilDepthPass = operation;
  12674. };
  12675. /**
  12676. * Sets a boolean indicating if the dithering state is enabled or disabled
  12677. * @param value defines the dithering state
  12678. */
  12679. Engine.prototype.setDitheringState = function (value) {
  12680. if (value) {
  12681. this._gl.enable(this._gl.DITHER);
  12682. }
  12683. else {
  12684. this._gl.disable(this._gl.DITHER);
  12685. }
  12686. };
  12687. /**
  12688. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12689. * @param value defines the rasterizer state
  12690. */
  12691. Engine.prototype.setRasterizerState = function (value) {
  12692. if (value) {
  12693. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12694. }
  12695. else {
  12696. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12697. }
  12698. };
  12699. /**
  12700. * stop executing a render loop function and remove it from the execution array
  12701. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12702. */
  12703. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12704. if (!renderFunction) {
  12705. this._activeRenderLoops = [];
  12706. return;
  12707. }
  12708. var index = this._activeRenderLoops.indexOf(renderFunction);
  12709. if (index >= 0) {
  12710. this._activeRenderLoops.splice(index, 1);
  12711. }
  12712. };
  12713. /** @hidden */
  12714. Engine.prototype._renderLoop = function () {
  12715. if (!this._contextWasLost) {
  12716. var shouldRender = true;
  12717. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12718. shouldRender = false;
  12719. }
  12720. if (shouldRender) {
  12721. // Start new frame
  12722. this.beginFrame();
  12723. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12724. var renderFunction = this._activeRenderLoops[index];
  12725. renderFunction();
  12726. }
  12727. // Present
  12728. this.endFrame();
  12729. }
  12730. }
  12731. if (this._activeRenderLoops.length > 0) {
  12732. // Register new frame
  12733. var requester = null;
  12734. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12735. requester = this._vrDisplay;
  12736. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12737. }
  12738. else {
  12739. this._renderingQueueLaunched = false;
  12740. }
  12741. };
  12742. /**
  12743. * Register and execute a render loop. The engine can have more than one render function
  12744. * @param renderFunction defines the function to continuously execute
  12745. */
  12746. Engine.prototype.runRenderLoop = function (renderFunction) {
  12747. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12748. return;
  12749. }
  12750. this._activeRenderLoops.push(renderFunction);
  12751. if (!this._renderingQueueLaunched) {
  12752. this._renderingQueueLaunched = true;
  12753. this._bindedRenderFunction = this._renderLoop.bind(this);
  12754. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12755. }
  12756. };
  12757. /**
  12758. * Toggle full screen mode
  12759. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12760. * @param options defines an option object to be sent to the requestFullscreen function
  12761. */
  12762. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12763. if (this.isFullscreen) {
  12764. BABYLON.Tools.ExitFullscreen();
  12765. }
  12766. else {
  12767. this._pointerLockRequested = requestPointerLock;
  12768. if (this._renderingCanvas) {
  12769. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12770. }
  12771. }
  12772. };
  12773. /**
  12774. * Clear the current render buffer or the current render target (if any is set up)
  12775. * @param color defines the color to use
  12776. * @param backBuffer defines if the back buffer must be cleared
  12777. * @param depth defines if the depth buffer must be cleared
  12778. * @param stencil defines if the stencil buffer must be cleared
  12779. */
  12780. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12781. if (stencil === void 0) { stencil = false; }
  12782. this.applyStates();
  12783. var mode = 0;
  12784. if (backBuffer && color) {
  12785. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12786. mode |= this._gl.COLOR_BUFFER_BIT;
  12787. }
  12788. if (depth) {
  12789. this._gl.clearDepth(1.0);
  12790. mode |= this._gl.DEPTH_BUFFER_BIT;
  12791. }
  12792. if (stencil) {
  12793. this._gl.clearStencil(0);
  12794. mode |= this._gl.STENCIL_BUFFER_BIT;
  12795. }
  12796. this._gl.clear(mode);
  12797. };
  12798. /**
  12799. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12800. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12801. * @param y defines the y-coordinate of the corner of the clear rectangle
  12802. * @param width defines the width of the clear rectangle
  12803. * @param height defines the height of the clear rectangle
  12804. * @param clearColor defines the clear color
  12805. */
  12806. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12807. var gl = this._gl;
  12808. // Save state
  12809. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12810. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12811. // Change state
  12812. gl.enable(gl.SCISSOR_TEST);
  12813. gl.scissor(x, y, width, height);
  12814. // Clear
  12815. this.clear(clearColor, true, true, true);
  12816. // Restore state
  12817. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12818. if (curScissor === true) {
  12819. gl.enable(gl.SCISSOR_TEST);
  12820. }
  12821. else {
  12822. gl.disable(gl.SCISSOR_TEST);
  12823. }
  12824. };
  12825. /**
  12826. * Set the WebGL's viewport
  12827. * @param viewport defines the viewport element to be used
  12828. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12829. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12830. */
  12831. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12832. var width = requiredWidth || this.getRenderWidth();
  12833. var height = requiredHeight || this.getRenderHeight();
  12834. var x = viewport.x || 0;
  12835. var y = viewport.y || 0;
  12836. this._cachedViewport = viewport;
  12837. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12838. };
  12839. /**
  12840. * Directly set the WebGL Viewport
  12841. * @param x defines the x coordinate of the viewport (in screen space)
  12842. * @param y defines the y coordinate of the viewport (in screen space)
  12843. * @param width defines the width of the viewport (in screen space)
  12844. * @param height defines the height of the viewport (in screen space)
  12845. * @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
  12846. */
  12847. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12848. var currentViewport = this._cachedViewport;
  12849. this._cachedViewport = null;
  12850. this._gl.viewport(x, y, width, height);
  12851. return currentViewport;
  12852. };
  12853. /**
  12854. * Begin a new frame
  12855. */
  12856. Engine.prototype.beginFrame = function () {
  12857. this.onBeginFrameObservable.notifyObservers(this);
  12858. this._measureFps();
  12859. };
  12860. /**
  12861. * Enf the current frame
  12862. */
  12863. Engine.prototype.endFrame = function () {
  12864. // Force a flush in case we are using a bad OS.
  12865. if (this._badOS) {
  12866. this.flushFramebuffer();
  12867. }
  12868. // Submit frame to the vr device, if enabled
  12869. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12870. // TODO: We should only submit the frame if we read frameData successfully.
  12871. this._vrDisplay.submitFrame();
  12872. }
  12873. this.onEndFrameObservable.notifyObservers(this);
  12874. };
  12875. /**
  12876. * Resize the view according to the canvas' size
  12877. */
  12878. Engine.prototype.resize = function () {
  12879. // We're not resizing the size of the canvas while in VR mode & presenting
  12880. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12881. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12882. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12883. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12884. }
  12885. };
  12886. /**
  12887. * Force a specific size of the canvas
  12888. * @param width defines the new canvas' width
  12889. * @param height defines the new canvas' height
  12890. */
  12891. Engine.prototype.setSize = function (width, height) {
  12892. if (!this._renderingCanvas) {
  12893. return;
  12894. }
  12895. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12896. return;
  12897. }
  12898. this._renderingCanvas.width = width;
  12899. this._renderingCanvas.height = height;
  12900. for (var index = 0; index < this.scenes.length; index++) {
  12901. var scene = this.scenes[index];
  12902. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12903. var cam = scene.cameras[camIndex];
  12904. cam._currentRenderId = 0;
  12905. }
  12906. }
  12907. if (this.onResizeObservable.hasObservers) {
  12908. this.onResizeObservable.notifyObservers(this);
  12909. }
  12910. };
  12911. // WebVR functions
  12912. /**
  12913. * Gets a boolean indicating if a webVR device was detected
  12914. * @returns true if a webVR device was detected
  12915. */
  12916. Engine.prototype.isVRDevicePresent = function () {
  12917. return !!this._vrDisplay;
  12918. };
  12919. /**
  12920. * Gets the current webVR device
  12921. * @returns the current webVR device (or null)
  12922. */
  12923. Engine.prototype.getVRDevice = function () {
  12924. return this._vrDisplay;
  12925. };
  12926. /**
  12927. * Initializes a webVR display and starts listening to display change events
  12928. * The onVRDisplayChangedObservable will be notified upon these changes
  12929. * @returns The onVRDisplayChangedObservable
  12930. */
  12931. Engine.prototype.initWebVR = function () {
  12932. this.initWebVRAsync();
  12933. return this.onVRDisplayChangedObservable;
  12934. };
  12935. /**
  12936. * Initializes a webVR display and starts listening to display change events
  12937. * The onVRDisplayChangedObservable will be notified upon these changes
  12938. * @returns A promise containing a VRDisplay and if vr is supported
  12939. */
  12940. Engine.prototype.initWebVRAsync = function () {
  12941. var _this = this;
  12942. var notifyObservers = function () {
  12943. var eventArgs = {
  12944. vrDisplay: _this._vrDisplay,
  12945. vrSupported: _this._vrSupported
  12946. };
  12947. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12948. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12949. };
  12950. if (!this._onVrDisplayConnect) {
  12951. this._onVrDisplayConnect = function (event) {
  12952. _this._vrDisplay = event.display;
  12953. notifyObservers();
  12954. };
  12955. this._onVrDisplayDisconnect = function () {
  12956. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12957. _this._vrDisplay = undefined;
  12958. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12959. notifyObservers();
  12960. };
  12961. this._onVrDisplayPresentChange = function () {
  12962. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12963. };
  12964. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12965. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12966. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12967. }
  12968. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12969. this._webVRInitPromise.then(notifyObservers);
  12970. return this._webVRInitPromise;
  12971. };
  12972. /**
  12973. * Call this function to switch to webVR mode
  12974. * Will do nothing if webVR is not supported or if there is no webVR device
  12975. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12976. */
  12977. Engine.prototype.enableVR = function () {
  12978. var _this = this;
  12979. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12980. var onResolved = function () {
  12981. _this.onVRRequestPresentComplete.notifyObservers(true);
  12982. _this._onVRFullScreenTriggered();
  12983. };
  12984. var onRejected = function () {
  12985. _this.onVRRequestPresentComplete.notifyObservers(false);
  12986. };
  12987. this.onVRRequestPresentStart.notifyObservers(this);
  12988. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12989. }
  12990. };
  12991. /**
  12992. * Call this function to leave webVR mode
  12993. * Will do nothing if webVR is not supported or if there is no webVR device
  12994. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12995. */
  12996. Engine.prototype.disableVR = function () {
  12997. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12998. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12999. }
  13000. };
  13001. Engine.prototype._getVRDisplaysAsync = function () {
  13002. var _this = this;
  13003. return new Promise(function (res, rej) {
  13004. if (navigator.getVRDisplays) {
  13005. navigator.getVRDisplays().then(function (devices) {
  13006. _this._vrSupported = true;
  13007. // note that devices may actually be an empty array. This is fine;
  13008. // we expect this._vrDisplay to be undefined in this case.
  13009. _this._vrDisplay = devices[0];
  13010. res({
  13011. vrDisplay: _this._vrDisplay,
  13012. vrSupported: _this._vrSupported
  13013. });
  13014. });
  13015. }
  13016. else {
  13017. _this._vrDisplay = undefined;
  13018. _this._vrSupported = false;
  13019. res({
  13020. vrDisplay: _this._vrDisplay,
  13021. vrSupported: _this._vrSupported
  13022. });
  13023. }
  13024. });
  13025. };
  13026. /**
  13027. * Binds the frame buffer to the specified texture.
  13028. * @param texture The texture to render to or null for the default canvas
  13029. * @param faceIndex The face of the texture to render to in case of cube texture
  13030. * @param requiredWidth The width of the target to render to
  13031. * @param requiredHeight The height of the target to render to
  13032. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13033. * @param depthStencilTexture The depth stencil texture to use to render
  13034. * @param lodLevel defines le lod level to bind to the frame buffer
  13035. */
  13036. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13037. if (lodLevel === void 0) { lodLevel = 0; }
  13038. if (this._currentRenderTarget) {
  13039. this.unBindFramebuffer(this._currentRenderTarget);
  13040. }
  13041. this._currentRenderTarget = texture;
  13042. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13043. var gl = this._gl;
  13044. if (texture.isCube) {
  13045. if (faceIndex === undefined) {
  13046. faceIndex = 0;
  13047. }
  13048. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13049. if (depthStencilTexture) {
  13050. if (depthStencilTexture._generateStencilBuffer) {
  13051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13052. }
  13053. else {
  13054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13055. }
  13056. }
  13057. }
  13058. if (this._cachedViewport && !forceFullscreenViewport) {
  13059. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13060. }
  13061. else {
  13062. if (!requiredWidth) {
  13063. requiredWidth = texture.width;
  13064. if (lodLevel) {
  13065. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13066. }
  13067. }
  13068. if (!requiredHeight) {
  13069. requiredHeight = texture.height;
  13070. if (lodLevel) {
  13071. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13072. }
  13073. }
  13074. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13075. }
  13076. this.wipeCaches();
  13077. };
  13078. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13079. if (this._currentFramebuffer !== framebuffer) {
  13080. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13081. this._currentFramebuffer = framebuffer;
  13082. }
  13083. };
  13084. /**
  13085. * Unbind the current render target texture from the webGL context
  13086. * @param texture defines the render target texture to unbind
  13087. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13088. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13089. */
  13090. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13091. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13092. this._currentRenderTarget = null;
  13093. // If MSAA, we need to bitblt back to main texture
  13094. var gl = this._gl;
  13095. if (texture._MSAAFramebuffer) {
  13096. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13097. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13098. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13099. }
  13100. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13101. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13102. gl.generateMipmap(gl.TEXTURE_2D);
  13103. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13104. }
  13105. if (onBeforeUnbind) {
  13106. if (texture._MSAAFramebuffer) {
  13107. // Bind the correct framebuffer
  13108. this.bindUnboundFramebuffer(texture._framebuffer);
  13109. }
  13110. onBeforeUnbind();
  13111. }
  13112. this.bindUnboundFramebuffer(null);
  13113. };
  13114. /**
  13115. * Unbind a list of render target textures from the webGL context
  13116. * This is used only when drawBuffer extension or webGL2 are active
  13117. * @param textures defines the render target textures to unbind
  13118. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13119. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13120. */
  13121. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13122. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13123. this._currentRenderTarget = null;
  13124. // If MSAA, we need to bitblt back to main texture
  13125. var gl = this._gl;
  13126. if (textures[0]._MSAAFramebuffer) {
  13127. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13128. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13129. var attachments = textures[0]._attachments;
  13130. if (!attachments) {
  13131. attachments = new Array(textures.length);
  13132. textures[0]._attachments = attachments;
  13133. }
  13134. for (var i = 0; i < textures.length; i++) {
  13135. var texture = textures[i];
  13136. for (var j = 0; j < attachments.length; j++) {
  13137. attachments[j] = gl.NONE;
  13138. }
  13139. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13140. gl.readBuffer(attachments[i]);
  13141. gl.drawBuffers(attachments);
  13142. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13143. }
  13144. for (var i = 0; i < attachments.length; i++) {
  13145. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13146. }
  13147. gl.drawBuffers(attachments);
  13148. }
  13149. for (var i = 0; i < textures.length; i++) {
  13150. var texture = textures[i];
  13151. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13152. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13153. gl.generateMipmap(gl.TEXTURE_2D);
  13154. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13155. }
  13156. }
  13157. if (onBeforeUnbind) {
  13158. if (textures[0]._MSAAFramebuffer) {
  13159. // Bind the correct framebuffer
  13160. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13161. }
  13162. onBeforeUnbind();
  13163. }
  13164. this.bindUnboundFramebuffer(null);
  13165. };
  13166. /**
  13167. * Force the mipmap generation for the given render target texture
  13168. * @param texture defines the render target texture to use
  13169. */
  13170. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13171. if (texture.generateMipMaps) {
  13172. var gl = this._gl;
  13173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13174. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13175. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13176. }
  13177. };
  13178. /**
  13179. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13180. */
  13181. Engine.prototype.flushFramebuffer = function () {
  13182. this._gl.flush();
  13183. };
  13184. /**
  13185. * Unbind the current render target and bind the default framebuffer
  13186. */
  13187. Engine.prototype.restoreDefaultFramebuffer = function () {
  13188. if (this._currentRenderTarget) {
  13189. this.unBindFramebuffer(this._currentRenderTarget);
  13190. }
  13191. else {
  13192. this.bindUnboundFramebuffer(null);
  13193. }
  13194. if (this._cachedViewport) {
  13195. this.setViewport(this._cachedViewport);
  13196. }
  13197. this.wipeCaches();
  13198. };
  13199. // UBOs
  13200. /**
  13201. * Create an uniform buffer
  13202. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13203. * @param elements defines the content of the uniform buffer
  13204. * @returns the webGL uniform buffer
  13205. */
  13206. Engine.prototype.createUniformBuffer = function (elements) {
  13207. var ubo = this._gl.createBuffer();
  13208. if (!ubo) {
  13209. throw new Error("Unable to create uniform buffer");
  13210. }
  13211. this.bindUniformBuffer(ubo);
  13212. if (elements instanceof Float32Array) {
  13213. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13214. }
  13215. else {
  13216. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13217. }
  13218. this.bindUniformBuffer(null);
  13219. ubo.references = 1;
  13220. return ubo;
  13221. };
  13222. /**
  13223. * Create a dynamic uniform buffer
  13224. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13225. * @param elements defines the content of the uniform buffer
  13226. * @returns the webGL uniform buffer
  13227. */
  13228. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13229. var ubo = this._gl.createBuffer();
  13230. if (!ubo) {
  13231. throw new Error("Unable to create dynamic uniform buffer");
  13232. }
  13233. this.bindUniformBuffer(ubo);
  13234. if (elements instanceof Float32Array) {
  13235. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13236. }
  13237. else {
  13238. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13239. }
  13240. this.bindUniformBuffer(null);
  13241. ubo.references = 1;
  13242. return ubo;
  13243. };
  13244. /**
  13245. * Update an existing uniform buffer
  13246. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13247. * @param uniformBuffer defines the target uniform buffer
  13248. * @param elements defines the content to update
  13249. * @param offset defines the offset in the uniform buffer where update should start
  13250. * @param count defines the size of the data to update
  13251. */
  13252. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13253. this.bindUniformBuffer(uniformBuffer);
  13254. if (offset === undefined) {
  13255. offset = 0;
  13256. }
  13257. if (count === undefined) {
  13258. if (elements instanceof Float32Array) {
  13259. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13260. }
  13261. else {
  13262. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13263. }
  13264. }
  13265. else {
  13266. if (elements instanceof Float32Array) {
  13267. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13268. }
  13269. else {
  13270. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13271. }
  13272. }
  13273. this.bindUniformBuffer(null);
  13274. };
  13275. // VBOs
  13276. Engine.prototype._resetVertexBufferBinding = function () {
  13277. this.bindArrayBuffer(null);
  13278. this._cachedVertexBuffers = null;
  13279. };
  13280. /**
  13281. * Creates a vertex buffer
  13282. * @param data the data for the vertex buffer
  13283. * @returns the new WebGL static buffer
  13284. */
  13285. Engine.prototype.createVertexBuffer = function (data) {
  13286. var vbo = this._gl.createBuffer();
  13287. if (!vbo) {
  13288. throw new Error("Unable to create vertex buffer");
  13289. }
  13290. this.bindArrayBuffer(vbo);
  13291. if (data instanceof Array) {
  13292. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13293. }
  13294. else {
  13295. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13296. }
  13297. this._resetVertexBufferBinding();
  13298. vbo.references = 1;
  13299. return vbo;
  13300. };
  13301. /**
  13302. * Creates a dynamic vertex buffer
  13303. * @param data the data for the dynamic vertex buffer
  13304. * @returns the new WebGL dynamic buffer
  13305. */
  13306. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13307. var vbo = this._gl.createBuffer();
  13308. if (!vbo) {
  13309. throw new Error("Unable to create dynamic vertex buffer");
  13310. }
  13311. this.bindArrayBuffer(vbo);
  13312. if (data instanceof Array) {
  13313. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13314. }
  13315. else {
  13316. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13317. }
  13318. this._resetVertexBufferBinding();
  13319. vbo.references = 1;
  13320. return vbo;
  13321. };
  13322. /**
  13323. * Update a dynamic index buffer
  13324. * @param indexBuffer defines the target index buffer
  13325. * @param indices defines the data to update
  13326. * @param offset defines the offset in the target index buffer where update should start
  13327. */
  13328. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13329. if (offset === void 0) { offset = 0; }
  13330. // Force cache update
  13331. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13332. this.bindIndexBuffer(indexBuffer);
  13333. var arrayBuffer;
  13334. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13335. arrayBuffer = indices;
  13336. }
  13337. else {
  13338. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13339. }
  13340. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13341. this._resetIndexBufferBinding();
  13342. };
  13343. /**
  13344. * Updates a dynamic vertex buffer.
  13345. * @param vertexBuffer the vertex buffer to update
  13346. * @param data the data used to update the vertex buffer
  13347. * @param byteOffset the byte offset of the data
  13348. * @param byteLength the byte length of the data
  13349. */
  13350. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13351. this.bindArrayBuffer(vertexBuffer);
  13352. if (byteOffset === undefined) {
  13353. byteOffset = 0;
  13354. }
  13355. if (byteLength === undefined) {
  13356. if (data instanceof Array) {
  13357. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13358. }
  13359. else {
  13360. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13361. }
  13362. }
  13363. else {
  13364. if (data instanceof Array) {
  13365. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13366. }
  13367. else {
  13368. if (data instanceof ArrayBuffer) {
  13369. data = new Uint8Array(data, byteOffset, byteLength);
  13370. }
  13371. else {
  13372. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13373. }
  13374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13375. }
  13376. }
  13377. this._resetVertexBufferBinding();
  13378. };
  13379. Engine.prototype._resetIndexBufferBinding = function () {
  13380. this.bindIndexBuffer(null);
  13381. this._cachedIndexBuffer = null;
  13382. };
  13383. /**
  13384. * Creates a new index buffer
  13385. * @param indices defines the content of the index buffer
  13386. * @param updatable defines if the index buffer must be updatable
  13387. * @returns a new webGL buffer
  13388. */
  13389. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13390. var vbo = this._gl.createBuffer();
  13391. if (!vbo) {
  13392. throw new Error("Unable to create index buffer");
  13393. }
  13394. this.bindIndexBuffer(vbo);
  13395. // Check for 32 bits indices
  13396. var arrayBuffer;
  13397. var need32Bits = false;
  13398. if (indices instanceof Uint16Array) {
  13399. arrayBuffer = indices;
  13400. }
  13401. else {
  13402. //check 32 bit support
  13403. if (this._caps.uintIndices) {
  13404. if (indices instanceof Uint32Array) {
  13405. arrayBuffer = indices;
  13406. need32Bits = true;
  13407. }
  13408. else {
  13409. //number[] or Int32Array, check if 32 bit is necessary
  13410. for (var index = 0; index < indices.length; index++) {
  13411. if (indices[index] > 65535) {
  13412. need32Bits = true;
  13413. break;
  13414. }
  13415. }
  13416. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13417. }
  13418. }
  13419. else {
  13420. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13421. arrayBuffer = new Uint16Array(indices);
  13422. }
  13423. }
  13424. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13425. this._resetIndexBufferBinding();
  13426. vbo.references = 1;
  13427. vbo.is32Bits = need32Bits;
  13428. return vbo;
  13429. };
  13430. /**
  13431. * Bind a webGL buffer to the webGL context
  13432. * @param buffer defines the buffer to bind
  13433. */
  13434. Engine.prototype.bindArrayBuffer = function (buffer) {
  13435. if (!this._vaoRecordInProgress) {
  13436. this._unbindVertexArrayObject();
  13437. }
  13438. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13439. };
  13440. /**
  13441. * Bind an uniform buffer to the current webGL context
  13442. * @param buffer defines the buffer to bind
  13443. */
  13444. Engine.prototype.bindUniformBuffer = function (buffer) {
  13445. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13446. };
  13447. /**
  13448. * Bind a buffer to the current webGL context at a given location
  13449. * @param buffer defines the buffer to bind
  13450. * @param location defines the index where to bind the buffer
  13451. */
  13452. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13453. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13454. };
  13455. /**
  13456. * Bind a specific block at a given index in a specific shader program
  13457. * @param shaderProgram defines the shader program
  13458. * @param blockName defines the block name
  13459. * @param index defines the index where to bind the block
  13460. */
  13461. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13462. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13463. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13464. };
  13465. ;
  13466. Engine.prototype.bindIndexBuffer = function (buffer) {
  13467. if (!this._vaoRecordInProgress) {
  13468. this._unbindVertexArrayObject();
  13469. }
  13470. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13471. };
  13472. Engine.prototype.bindBuffer = function (buffer, target) {
  13473. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13474. this._gl.bindBuffer(target, buffer);
  13475. this._currentBoundBuffer[target] = buffer;
  13476. }
  13477. };
  13478. /**
  13479. * update the bound buffer with the given data
  13480. * @param data defines the data to update
  13481. */
  13482. Engine.prototype.updateArrayBuffer = function (data) {
  13483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13484. };
  13485. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13486. var pointer = this._currentBufferPointers[indx];
  13487. var changed = false;
  13488. if (!pointer.active) {
  13489. changed = true;
  13490. pointer.active = true;
  13491. pointer.index = indx;
  13492. pointer.size = size;
  13493. pointer.type = type;
  13494. pointer.normalized = normalized;
  13495. pointer.stride = stride;
  13496. pointer.offset = offset;
  13497. pointer.buffer = buffer;
  13498. }
  13499. else {
  13500. if (pointer.buffer !== buffer) {
  13501. pointer.buffer = buffer;
  13502. changed = true;
  13503. }
  13504. if (pointer.size !== size) {
  13505. pointer.size = size;
  13506. changed = true;
  13507. }
  13508. if (pointer.type !== type) {
  13509. pointer.type = type;
  13510. changed = true;
  13511. }
  13512. if (pointer.normalized !== normalized) {
  13513. pointer.normalized = normalized;
  13514. changed = true;
  13515. }
  13516. if (pointer.stride !== stride) {
  13517. pointer.stride = stride;
  13518. changed = true;
  13519. }
  13520. if (pointer.offset !== offset) {
  13521. pointer.offset = offset;
  13522. changed = true;
  13523. }
  13524. }
  13525. if (changed || this._vaoRecordInProgress) {
  13526. this.bindArrayBuffer(buffer);
  13527. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13528. }
  13529. };
  13530. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13531. if (indexBuffer == null) {
  13532. return;
  13533. }
  13534. if (this._cachedIndexBuffer !== indexBuffer) {
  13535. this._cachedIndexBuffer = indexBuffer;
  13536. this.bindIndexBuffer(indexBuffer);
  13537. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13538. }
  13539. };
  13540. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13541. var attributes = effect.getAttributesNames();
  13542. if (!this._vaoRecordInProgress) {
  13543. this._unbindVertexArrayObject();
  13544. }
  13545. this.unbindAllAttributes();
  13546. for (var index = 0; index < attributes.length; index++) {
  13547. var order = effect.getAttributeLocation(index);
  13548. if (order >= 0) {
  13549. var vertexBuffer = vertexBuffers[attributes[index]];
  13550. if (!vertexBuffer) {
  13551. continue;
  13552. }
  13553. this._gl.enableVertexAttribArray(order);
  13554. if (!this._vaoRecordInProgress) {
  13555. this._vertexAttribArraysEnabled[order] = true;
  13556. }
  13557. var buffer = vertexBuffer.getBuffer();
  13558. if (buffer) {
  13559. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13560. if (vertexBuffer.getIsInstanced()) {
  13561. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13562. if (!this._vaoRecordInProgress) {
  13563. this._currentInstanceLocations.push(order);
  13564. this._currentInstanceBuffers.push(buffer);
  13565. }
  13566. }
  13567. }
  13568. }
  13569. }
  13570. };
  13571. /**
  13572. * Records a vertex array object
  13573. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13574. * @param vertexBuffers defines the list of vertex buffers to store
  13575. * @param indexBuffer defines the index buffer to store
  13576. * @param effect defines the effect to store
  13577. * @returns the new vertex array object
  13578. */
  13579. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13580. var vao = this._gl.createVertexArray();
  13581. this._vaoRecordInProgress = true;
  13582. this._gl.bindVertexArray(vao);
  13583. this._mustWipeVertexAttributes = true;
  13584. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13585. this.bindIndexBuffer(indexBuffer);
  13586. this._vaoRecordInProgress = false;
  13587. this._gl.bindVertexArray(null);
  13588. return vao;
  13589. };
  13590. /**
  13591. * Bind a specific vertex array object
  13592. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13593. * @param vertexArrayObject defines the vertex array object to bind
  13594. * @param indexBuffer defines the index buffer to bind
  13595. */
  13596. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13597. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13598. this._cachedVertexArrayObject = vertexArrayObject;
  13599. this._gl.bindVertexArray(vertexArrayObject);
  13600. this._cachedVertexBuffers = null;
  13601. this._cachedIndexBuffer = null;
  13602. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13603. this._mustWipeVertexAttributes = true;
  13604. }
  13605. };
  13606. /**
  13607. * Bind webGl buffers directly to the webGL context
  13608. * @param vertexBuffer defines the vertex buffer to bind
  13609. * @param indexBuffer defines the index buffer to bind
  13610. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13611. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13612. * @param effect defines the effect associated with the vertex buffer
  13613. */
  13614. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13615. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13616. this._cachedVertexBuffers = vertexBuffer;
  13617. this._cachedEffectForVertexBuffers = effect;
  13618. var attributesCount = effect.getAttributesCount();
  13619. this._unbindVertexArrayObject();
  13620. this.unbindAllAttributes();
  13621. var offset = 0;
  13622. for (var index = 0; index < attributesCount; index++) {
  13623. if (index < vertexDeclaration.length) {
  13624. var order = effect.getAttributeLocation(index);
  13625. if (order >= 0) {
  13626. this._gl.enableVertexAttribArray(order);
  13627. this._vertexAttribArraysEnabled[order] = true;
  13628. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13629. }
  13630. offset += vertexDeclaration[index] * 4;
  13631. }
  13632. }
  13633. }
  13634. this._bindIndexBufferWithCache(indexBuffer);
  13635. };
  13636. Engine.prototype._unbindVertexArrayObject = function () {
  13637. if (!this._cachedVertexArrayObject) {
  13638. return;
  13639. }
  13640. this._cachedVertexArrayObject = null;
  13641. this._gl.bindVertexArray(null);
  13642. };
  13643. /**
  13644. * Bind a list of vertex buffers to the webGL context
  13645. * @param vertexBuffers defines the list of vertex buffers to bind
  13646. * @param indexBuffer defines the index buffer to bind
  13647. * @param effect defines the effect associated with the vertex buffers
  13648. */
  13649. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13650. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13651. this._cachedVertexBuffers = vertexBuffers;
  13652. this._cachedEffectForVertexBuffers = effect;
  13653. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13654. }
  13655. this._bindIndexBufferWithCache(indexBuffer);
  13656. };
  13657. /**
  13658. * Unbind all instance attributes
  13659. */
  13660. Engine.prototype.unbindInstanceAttributes = function () {
  13661. var boundBuffer;
  13662. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13663. var instancesBuffer = this._currentInstanceBuffers[i];
  13664. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13665. boundBuffer = instancesBuffer;
  13666. this.bindArrayBuffer(instancesBuffer);
  13667. }
  13668. var offsetLocation = this._currentInstanceLocations[i];
  13669. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13670. }
  13671. this._currentInstanceBuffers.length = 0;
  13672. this._currentInstanceLocations.length = 0;
  13673. };
  13674. /**
  13675. * Release and free the memory of a vertex array object
  13676. * @param vao defines the vertex array object to delete
  13677. */
  13678. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13679. this._gl.deleteVertexArray(vao);
  13680. };
  13681. /** @hidden */
  13682. Engine.prototype._releaseBuffer = function (buffer) {
  13683. buffer.references--;
  13684. if (buffer.references === 0) {
  13685. this._gl.deleteBuffer(buffer);
  13686. return true;
  13687. }
  13688. return false;
  13689. };
  13690. /**
  13691. * Creates a webGL buffer to use with instanciation
  13692. * @param capacity defines the size of the buffer
  13693. * @returns the webGL buffer
  13694. */
  13695. Engine.prototype.createInstancesBuffer = function (capacity) {
  13696. var buffer = this._gl.createBuffer();
  13697. if (!buffer) {
  13698. throw new Error("Unable to create instance buffer");
  13699. }
  13700. buffer.capacity = capacity;
  13701. this.bindArrayBuffer(buffer);
  13702. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13703. return buffer;
  13704. };
  13705. /**
  13706. * Delete a webGL buffer used with instanciation
  13707. * @param buffer defines the webGL buffer to delete
  13708. */
  13709. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13710. this._gl.deleteBuffer(buffer);
  13711. };
  13712. /**
  13713. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13714. * @param instancesBuffer defines the webGL buffer to update and bind
  13715. * @param data defines the data to store in the buffer
  13716. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13717. */
  13718. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13719. this.bindArrayBuffer(instancesBuffer);
  13720. if (data) {
  13721. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13722. }
  13723. if (offsetLocations[0].index !== undefined) {
  13724. var stride = 0;
  13725. for (var i = 0; i < offsetLocations.length; i++) {
  13726. var ai = offsetLocations[i];
  13727. stride += ai.attributeSize * 4;
  13728. }
  13729. for (var i = 0; i < offsetLocations.length; i++) {
  13730. var ai = offsetLocations[i];
  13731. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13732. this._gl.enableVertexAttribArray(ai.index);
  13733. this._vertexAttribArraysEnabled[ai.index] = true;
  13734. }
  13735. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13736. this._gl.vertexAttribDivisor(ai.index, 1);
  13737. this._currentInstanceLocations.push(ai.index);
  13738. this._currentInstanceBuffers.push(instancesBuffer);
  13739. }
  13740. }
  13741. else {
  13742. for (var index = 0; index < 4; index++) {
  13743. var offsetLocation = offsetLocations[index];
  13744. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13745. this._gl.enableVertexAttribArray(offsetLocation);
  13746. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13747. }
  13748. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13749. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13750. this._currentInstanceLocations.push(offsetLocation);
  13751. this._currentInstanceBuffers.push(instancesBuffer);
  13752. }
  13753. }
  13754. };
  13755. /**
  13756. * Apply all cached states (depth, culling, stencil and alpha)
  13757. */
  13758. Engine.prototype.applyStates = function () {
  13759. this._depthCullingState.apply(this._gl);
  13760. this._stencilState.apply(this._gl);
  13761. this._alphaState.apply(this._gl);
  13762. };
  13763. /**
  13764. * Send a draw order
  13765. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13766. * @param indexStart defines the starting index
  13767. * @param indexCount defines the number of index to draw
  13768. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13769. */
  13770. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13771. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13772. };
  13773. /**
  13774. * Draw a list of points
  13775. * @param verticesStart defines the index of first vertex to draw
  13776. * @param verticesCount defines the count of vertices to draw
  13777. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13778. */
  13779. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13780. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13781. };
  13782. /**
  13783. * Draw a list of unindexed primitives
  13784. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13785. * @param verticesStart defines the index of first vertex to draw
  13786. * @param verticesCount defines the count of vertices to draw
  13787. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13788. */
  13789. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13790. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13791. };
  13792. /**
  13793. * Draw a list of indexed primitives
  13794. * @param fillMode defines the primitive to use
  13795. * @param indexStart defines the starting index
  13796. * @param indexCount defines the number of index to draw
  13797. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13798. */
  13799. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13800. // Apply states
  13801. this.applyStates();
  13802. this._drawCalls.addCount(1, false);
  13803. // Render
  13804. var drawMode = this._drawMode(fillMode);
  13805. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13806. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13807. if (instancesCount) {
  13808. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13809. }
  13810. else {
  13811. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13812. }
  13813. };
  13814. /**
  13815. * Draw a list of unindexed primitives
  13816. * @param fillMode defines the primitive to use
  13817. * @param verticesStart defines the index of first vertex to draw
  13818. * @param verticesCount defines the count of vertices to draw
  13819. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13820. */
  13821. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13822. // Apply states
  13823. this.applyStates();
  13824. this._drawCalls.addCount(1, false);
  13825. var drawMode = this._drawMode(fillMode);
  13826. if (instancesCount) {
  13827. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13828. }
  13829. else {
  13830. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13831. }
  13832. };
  13833. Engine.prototype._drawMode = function (fillMode) {
  13834. switch (fillMode) {
  13835. // Triangle views
  13836. case BABYLON.Material.TriangleFillMode:
  13837. return this._gl.TRIANGLES;
  13838. case BABYLON.Material.PointFillMode:
  13839. return this._gl.POINTS;
  13840. case BABYLON.Material.WireFrameFillMode:
  13841. return this._gl.LINES;
  13842. // Draw modes
  13843. case BABYLON.Material.PointListDrawMode:
  13844. return this._gl.POINTS;
  13845. case BABYLON.Material.LineListDrawMode:
  13846. return this._gl.LINES;
  13847. case BABYLON.Material.LineLoopDrawMode:
  13848. return this._gl.LINE_LOOP;
  13849. case BABYLON.Material.LineStripDrawMode:
  13850. return this._gl.LINE_STRIP;
  13851. case BABYLON.Material.TriangleStripDrawMode:
  13852. return this._gl.TRIANGLE_STRIP;
  13853. case BABYLON.Material.TriangleFanDrawMode:
  13854. return this._gl.TRIANGLE_FAN;
  13855. default:
  13856. return this._gl.TRIANGLES;
  13857. }
  13858. };
  13859. // Shaders
  13860. /** @hidden */
  13861. Engine.prototype._releaseEffect = function (effect) {
  13862. if (this._compiledEffects[effect._key]) {
  13863. delete this._compiledEffects[effect._key];
  13864. this._deleteProgram(effect.getProgram());
  13865. }
  13866. };
  13867. /** @hidden */
  13868. Engine.prototype._deleteProgram = function (program) {
  13869. if (program) {
  13870. program.__SPECTOR_rebuildProgram = null;
  13871. if (program.transformFeedback) {
  13872. this.deleteTransformFeedback(program.transformFeedback);
  13873. program.transformFeedback = null;
  13874. }
  13875. this._gl.deleteProgram(program);
  13876. }
  13877. };
  13878. /**
  13879. * Create a new effect (used to store vertex/fragment shaders)
  13880. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13881. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13882. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13883. * @param samplers defines an array of string used to represent textures
  13884. * @param defines defines the string containing the defines to use to compile the shaders
  13885. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13886. * @param onCompiled defines a function to call when the effect creation is successful
  13887. * @param onError defines a function to call when the effect creation has failed
  13888. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13889. * @returns the new Effect
  13890. */
  13891. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13892. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13893. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13894. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13895. if (this._compiledEffects[name]) {
  13896. var compiledEffect = this._compiledEffects[name];
  13897. if (onCompiled && compiledEffect.isReady()) {
  13898. onCompiled(compiledEffect);
  13899. }
  13900. return compiledEffect;
  13901. }
  13902. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13903. effect._key = name;
  13904. this._compiledEffects[name] = effect;
  13905. return effect;
  13906. };
  13907. /**
  13908. * Create an effect to use with particle systems
  13909. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13910. * @param uniformsNames defines a list of attribute names
  13911. * @param samplers defines an array of string used to represent textures
  13912. * @param defines defines the string containing the defines to use to compile the shaders
  13913. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13914. * @param onCompiled defines a function to call when the effect creation is successful
  13915. * @param onError defines a function to call when the effect creation has failed
  13916. * @returns the new Effect
  13917. */
  13918. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13919. if (uniformsNames === void 0) { uniformsNames = []; }
  13920. if (samplers === void 0) { samplers = []; }
  13921. if (defines === void 0) { defines = ""; }
  13922. return this.createEffect({
  13923. vertex: "particles",
  13924. fragmentElement: fragmentName
  13925. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13926. };
  13927. /**
  13928. * Directly creates a webGL program
  13929. * @param vertexCode defines the vertex shader code to use
  13930. * @param fragmentCode defines the fragment shader code to use
  13931. * @param context defines the webGL context to use (if not set, the current one will be used)
  13932. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13933. * @returns the new webGL program
  13934. */
  13935. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13936. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13937. context = context || this._gl;
  13938. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13939. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13940. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13941. };
  13942. /**
  13943. * Creates a webGL program
  13944. * @param vertexCode defines the vertex shader code to use
  13945. * @param fragmentCode defines the fragment shader code to use
  13946. * @param defines defines the string containing the defines to use to compile the shaders
  13947. * @param context defines the webGL context to use (if not set, the current one will be used)
  13948. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13949. * @returns the new webGL program
  13950. */
  13951. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13952. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13953. context = context || this._gl;
  13954. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13955. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13956. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13957. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13958. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13959. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13960. return program;
  13961. };
  13962. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13963. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13964. var shaderProgram = context.createProgram();
  13965. if (!shaderProgram) {
  13966. throw new Error("Unable to create program");
  13967. }
  13968. context.attachShader(shaderProgram, vertexShader);
  13969. context.attachShader(shaderProgram, fragmentShader);
  13970. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13971. var transformFeedback = this.createTransformFeedback();
  13972. this.bindTransformFeedback(transformFeedback);
  13973. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13974. shaderProgram.transformFeedback = transformFeedback;
  13975. }
  13976. context.linkProgram(shaderProgram);
  13977. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13978. this.bindTransformFeedback(null);
  13979. }
  13980. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13981. if (!linked) {
  13982. context.validateProgram(shaderProgram);
  13983. var error = context.getProgramInfoLog(shaderProgram);
  13984. if (error) {
  13985. throw new Error(error);
  13986. }
  13987. }
  13988. context.deleteShader(vertexShader);
  13989. context.deleteShader(fragmentShader);
  13990. return shaderProgram;
  13991. };
  13992. /**
  13993. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13994. * @param shaderProgram defines the webGL program to use
  13995. * @param uniformsNames defines the list of uniform names
  13996. * @returns an array of webGL uniform locations
  13997. */
  13998. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13999. var results = new Array();
  14000. for (var index = 0; index < uniformsNames.length; index++) {
  14001. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14002. }
  14003. return results;
  14004. };
  14005. /**
  14006. * Gets the lsit of active attributes for a given webGL program
  14007. * @param shaderProgram defines the webGL program to use
  14008. * @param attributesNames defines the list of attribute names to get
  14009. * @returns an array of indices indicating the offset of each attribute
  14010. */
  14011. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14012. var results = [];
  14013. for (var index = 0; index < attributesNames.length; index++) {
  14014. try {
  14015. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14016. }
  14017. catch (e) {
  14018. results.push(-1);
  14019. }
  14020. }
  14021. return results;
  14022. };
  14023. /**
  14024. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14025. * @param effect defines the effect to activate
  14026. */
  14027. Engine.prototype.enableEffect = function (effect) {
  14028. if (!effect) {
  14029. return;
  14030. }
  14031. // Use program
  14032. this.bindSamplers(effect);
  14033. this._currentEffect = effect;
  14034. if (effect.onBind) {
  14035. effect.onBind(effect);
  14036. }
  14037. effect.onBindObservable.notifyObservers(effect);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of int32
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of int32 to store
  14043. */
  14044. Engine.prototype.setIntArray = function (uniform, array) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniform1iv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of int32 (stored as vec2)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of int32 to store
  14053. */
  14054. Engine.prototype.setIntArray2 = function (uniform, array) {
  14055. if (!uniform || array.length % 2 !== 0)
  14056. return;
  14057. this._gl.uniform2iv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of int32 (stored as vec3)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of int32 to store
  14063. */
  14064. Engine.prototype.setIntArray3 = function (uniform, array) {
  14065. if (!uniform || array.length % 3 !== 0)
  14066. return;
  14067. this._gl.uniform3iv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of int32 (stored as vec4)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of int32 to store
  14073. */
  14074. Engine.prototype.setIntArray4 = function (uniform, array) {
  14075. if (!uniform || array.length % 4 !== 0)
  14076. return;
  14077. this._gl.uniform4iv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of float32
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of float32 to store
  14083. */
  14084. Engine.prototype.setFloatArray = function (uniform, array) {
  14085. if (!uniform)
  14086. return;
  14087. this._gl.uniform1fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of float32 (stored as vec2)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of float32 to store
  14093. */
  14094. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14095. if (!uniform || array.length % 2 !== 0)
  14096. return;
  14097. this._gl.uniform2fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of float32 (stored as vec3)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of float32 to store
  14103. */
  14104. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14105. if (!uniform || array.length % 3 !== 0)
  14106. return;
  14107. this._gl.uniform3fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of float32 (stored as vec4)
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of float32 to store
  14113. */
  14114. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14115. if (!uniform || array.length % 4 !== 0)
  14116. return;
  14117. this._gl.uniform4fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of number
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param array defines the array of number to store
  14123. */
  14124. Engine.prototype.setArray = function (uniform, array) {
  14125. if (!uniform)
  14126. return;
  14127. this._gl.uniform1fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of number (stored as vec2)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param array defines the array of number to store
  14133. */
  14134. Engine.prototype.setArray2 = function (uniform, array) {
  14135. if (!uniform || array.length % 2 !== 0)
  14136. return;
  14137. this._gl.uniform2fv(uniform, array);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to an array of number (stored as vec3)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param array defines the array of number to store
  14143. */
  14144. Engine.prototype.setArray3 = function (uniform, array) {
  14145. if (!uniform || array.length % 3 !== 0)
  14146. return;
  14147. this._gl.uniform3fv(uniform, array);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to an array of number (stored as vec4)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param array defines the array of number to store
  14153. */
  14154. Engine.prototype.setArray4 = function (uniform, array) {
  14155. if (!uniform || array.length % 4 !== 0)
  14156. return;
  14157. this._gl.uniform4fv(uniform, array);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to an array of float32 (stored as matrices)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param matrices defines the array of float32 to store
  14163. */
  14164. Engine.prototype.setMatrices = function (uniform, matrices) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a matrix
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param matrix defines the matrix to store
  14173. */
  14174. Engine.prototype.setMatrix = function (uniform, matrix) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a matrix (3x3)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14183. */
  14184. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a matrix (2x2)
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14193. */
  14194. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a number (int)
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param value defines the int number to store
  14203. */
  14204. Engine.prototype.setInt = function (uniform, value) {
  14205. if (!uniform)
  14206. return;
  14207. this._gl.uniform1i(uniform, value);
  14208. };
  14209. /**
  14210. * Set the value of an uniform to a number (float)
  14211. * @param uniform defines the webGL uniform location where to store the value
  14212. * @param value defines the float number to store
  14213. */
  14214. Engine.prototype.setFloat = function (uniform, value) {
  14215. if (!uniform)
  14216. return;
  14217. this._gl.uniform1f(uniform, value);
  14218. };
  14219. /**
  14220. * Set the value of an uniform to a vec2
  14221. * @param uniform defines the webGL uniform location where to store the value
  14222. * @param x defines the 1st component of the value
  14223. * @param y defines the 2nd component of the value
  14224. */
  14225. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14226. if (!uniform)
  14227. return;
  14228. this._gl.uniform2f(uniform, x, y);
  14229. };
  14230. /**
  14231. * Set the value of an uniform to a vec3
  14232. * @param uniform defines the webGL uniform location where to store the value
  14233. * @param x defines the 1st component of the value
  14234. * @param y defines the 2nd component of the value
  14235. * @param z defines the 3rd component of the value
  14236. */
  14237. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14238. if (!uniform)
  14239. return;
  14240. this._gl.uniform3f(uniform, x, y, z);
  14241. };
  14242. /**
  14243. * Set the value of an uniform to a boolean
  14244. * @param uniform defines the webGL uniform location where to store the value
  14245. * @param bool defines the boolean to store
  14246. */
  14247. Engine.prototype.setBool = function (uniform, bool) {
  14248. if (!uniform)
  14249. return;
  14250. this._gl.uniform1i(uniform, bool);
  14251. };
  14252. /**
  14253. * Set the value of an uniform to a vec4
  14254. * @param uniform defines the webGL uniform location where to store the value
  14255. * @param x defines the 1st component of the value
  14256. * @param y defines the 2nd component of the value
  14257. * @param z defines the 3rd component of the value
  14258. * @param w defines the 4th component of the value
  14259. */
  14260. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14261. if (!uniform)
  14262. return;
  14263. this._gl.uniform4f(uniform, x, y, z, w);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to a Color3
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param color3 defines the color to store
  14269. */
  14270. Engine.prototype.setColor3 = function (uniform, color3) {
  14271. if (!uniform)
  14272. return;
  14273. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14274. };
  14275. /**
  14276. * Set the value of an uniform to a Color3 and an alpha value
  14277. * @param uniform defines the webGL uniform location where to store the value
  14278. * @param color3 defines the color to store
  14279. * @param alpha defines the alpha component to store
  14280. */
  14281. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14282. if (!uniform)
  14283. return;
  14284. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14285. };
  14286. /**
  14287. * Sets a Color4 on a uniform variable
  14288. * @param uniform defines the uniform location
  14289. * @param color4 defines the value to be set
  14290. */
  14291. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14292. if (!uniform)
  14293. return;
  14294. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14295. };
  14296. // States
  14297. /**
  14298. * Set various states to the webGL context
  14299. * @param culling defines backface culling state
  14300. * @param zOffset defines the value to apply to zOffset (0 by default)
  14301. * @param force defines if states must be applied even if cache is up to date
  14302. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14303. */
  14304. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14305. if (zOffset === void 0) { zOffset = 0; }
  14306. if (reverseSide === void 0) { reverseSide = false; }
  14307. // Culling
  14308. if (this._depthCullingState.cull !== culling || force) {
  14309. this._depthCullingState.cull = culling;
  14310. }
  14311. // Cull face
  14312. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14313. if (this._depthCullingState.cullFace !== cullFace || force) {
  14314. this._depthCullingState.cullFace = cullFace;
  14315. }
  14316. // Z offset
  14317. this.setZOffset(zOffset);
  14318. // Front face
  14319. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14320. if (this._depthCullingState.frontFace !== frontFace || force) {
  14321. this._depthCullingState.frontFace = frontFace;
  14322. }
  14323. };
  14324. /**
  14325. * Set the z offset to apply to current rendering
  14326. * @param value defines the offset to apply
  14327. */
  14328. Engine.prototype.setZOffset = function (value) {
  14329. this._depthCullingState.zOffset = value;
  14330. };
  14331. /**
  14332. * Gets the current value of the zOffset
  14333. * @returns the current zOffset state
  14334. */
  14335. Engine.prototype.getZOffset = function () {
  14336. return this._depthCullingState.zOffset;
  14337. };
  14338. /**
  14339. * Enable or disable depth buffering
  14340. * @param enable defines the state to set
  14341. */
  14342. Engine.prototype.setDepthBuffer = function (enable) {
  14343. this._depthCullingState.depthTest = enable;
  14344. };
  14345. /**
  14346. * Gets a boolean indicating if depth writing is enabled
  14347. * @returns the current depth writing state
  14348. */
  14349. Engine.prototype.getDepthWrite = function () {
  14350. return this._depthCullingState.depthMask;
  14351. };
  14352. /**
  14353. * Enable or disable depth writing
  14354. * @param enable defines the state to set
  14355. */
  14356. Engine.prototype.setDepthWrite = function (enable) {
  14357. this._depthCullingState.depthMask = enable;
  14358. };
  14359. /**
  14360. * Enable or disable color writing
  14361. * @param enable defines the state to set
  14362. */
  14363. Engine.prototype.setColorWrite = function (enable) {
  14364. this._gl.colorMask(enable, enable, enable, enable);
  14365. this._colorWrite = enable;
  14366. };
  14367. /**
  14368. * Gets a boolean indicating if color writing is enabled
  14369. * @returns the current color writing state
  14370. */
  14371. Engine.prototype.getColorWrite = function () {
  14372. return this._colorWrite;
  14373. };
  14374. /**
  14375. * Sets alpha constants used by some alpha blending modes
  14376. * @param r defines the red component
  14377. * @param g defines the green component
  14378. * @param b defines the blue component
  14379. * @param a defines the alpha component
  14380. */
  14381. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14382. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14383. };
  14384. /**
  14385. * Sets the current alpha mode
  14386. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14387. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14388. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14389. */
  14390. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14391. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14392. if (this._alphaMode === mode) {
  14393. return;
  14394. }
  14395. switch (mode) {
  14396. case Engine.ALPHA_DISABLE:
  14397. this._alphaState.alphaBlend = false;
  14398. break;
  14399. case Engine.ALPHA_PREMULTIPLIED:
  14400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14401. this._alphaState.alphaBlend = true;
  14402. break;
  14403. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14405. this._alphaState.alphaBlend = true;
  14406. break;
  14407. case Engine.ALPHA_COMBINE:
  14408. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14409. this._alphaState.alphaBlend = true;
  14410. break;
  14411. case Engine.ALPHA_ONEONE:
  14412. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14413. this._alphaState.alphaBlend = true;
  14414. break;
  14415. case Engine.ALPHA_ADD:
  14416. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14417. this._alphaState.alphaBlend = true;
  14418. break;
  14419. case Engine.ALPHA_SUBTRACT:
  14420. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14421. this._alphaState.alphaBlend = true;
  14422. break;
  14423. case Engine.ALPHA_MULTIPLY:
  14424. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14425. this._alphaState.alphaBlend = true;
  14426. break;
  14427. case Engine.ALPHA_MAXIMIZED:
  14428. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14429. this._alphaState.alphaBlend = true;
  14430. break;
  14431. case Engine.ALPHA_INTERPOLATE:
  14432. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14433. this._alphaState.alphaBlend = true;
  14434. break;
  14435. case Engine.ALPHA_SCREENMODE:
  14436. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14437. this._alphaState.alphaBlend = true;
  14438. break;
  14439. }
  14440. if (!noDepthWriteChange) {
  14441. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14442. }
  14443. this._alphaMode = mode;
  14444. };
  14445. /**
  14446. * Gets the current alpha mode
  14447. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14448. * @returns the current alpha mode
  14449. */
  14450. Engine.prototype.getAlphaMode = function () {
  14451. return this._alphaMode;
  14452. };
  14453. // Textures
  14454. /**
  14455. * Force the entire cache to be cleared
  14456. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14457. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14458. */
  14459. Engine.prototype.wipeCaches = function (bruteForce) {
  14460. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14461. return;
  14462. }
  14463. this._currentEffect = null;
  14464. if (bruteForce) {
  14465. this.resetTextureCache();
  14466. this._currentProgram = null;
  14467. this._stencilState.reset();
  14468. this._depthCullingState.reset();
  14469. this.setDepthFunctionToLessOrEqual();
  14470. this._alphaState.reset();
  14471. }
  14472. this._resetVertexBufferBinding();
  14473. this._cachedIndexBuffer = null;
  14474. this._cachedEffectForVertexBuffers = null;
  14475. this._unbindVertexArrayObject();
  14476. this.bindIndexBuffer(null);
  14477. };
  14478. /**
  14479. * Set the compressed texture format to use, based on the formats you have, and the formats
  14480. * supported by the hardware / browser.
  14481. *
  14482. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14483. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14484. * to API arguments needed to compressed textures. This puts the burden on the container
  14485. * generator to house the arcane code for determining these for current & future formats.
  14486. *
  14487. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14488. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14489. *
  14490. * Note: The result of this call is not taken into account when a texture is base64.
  14491. *
  14492. * @param formatsAvailable defines the list of those format families you have created
  14493. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14494. *
  14495. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14496. * @returns The extension selected.
  14497. */
  14498. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14499. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14500. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14501. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14502. return this._textureFormatInUse = this._texturesSupported[i];
  14503. }
  14504. }
  14505. }
  14506. // actively set format to nothing, to allow this to be called more than once
  14507. // and possibly fail the 2nd time
  14508. this._textureFormatInUse = null;
  14509. return null;
  14510. };
  14511. /** @hidden */
  14512. Engine.prototype._createTexture = function () {
  14513. var texture = this._gl.createTexture();
  14514. if (!texture) {
  14515. throw new Error("Unable to create texture");
  14516. }
  14517. return texture;
  14518. };
  14519. /**
  14520. * Usually called from BABYLON.Texture.ts.
  14521. * Passed information to create a WebGLTexture
  14522. * @param urlArg defines a value which contains one of the following:
  14523. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14524. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14525. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14526. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14527. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14528. * @param scene needed for loading to the correct scene
  14529. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14530. * @param onLoad optional callback to be called upon successful completion
  14531. * @param onError optional callback to be called upon failure
  14532. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14533. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14534. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14535. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14536. */
  14537. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14538. var _this = this;
  14539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14540. if (onLoad === void 0) { onLoad = null; }
  14541. if (onError === void 0) { onError = null; }
  14542. if (buffer === void 0) { buffer = null; }
  14543. if (fallback === void 0) { fallback = null; }
  14544. if (format === void 0) { format = null; }
  14545. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14546. var fromData = url.substr(0, 5) === "data:";
  14547. var fromBlob = url.substr(0, 5) === "blob:";
  14548. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14549. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14550. // establish the file extension, if possible
  14551. var lastDot = url.lastIndexOf('.');
  14552. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14553. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14554. var isTGA = (extension.indexOf(".tga") === 0);
  14555. // determine if a ktx file should be substituted
  14556. var isKTX = false;
  14557. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14558. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14559. isKTX = true;
  14560. }
  14561. if (scene) {
  14562. scene._addPendingData(texture);
  14563. }
  14564. texture.url = url;
  14565. texture.generateMipMaps = !noMipmap;
  14566. texture.samplingMode = samplingMode;
  14567. texture.invertY = invertY;
  14568. if (!this._doNotHandleContextLost) {
  14569. // Keep a link to the buffer only if we plan to handle context lost
  14570. texture._buffer = buffer;
  14571. }
  14572. var onLoadObserver = null;
  14573. if (onLoad && !fallback) {
  14574. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14575. }
  14576. if (!fallback)
  14577. this._internalTexturesCache.push(texture);
  14578. var onerror = function (message, exception) {
  14579. if (scene) {
  14580. scene._removePendingData(texture);
  14581. }
  14582. if (onLoadObserver) {
  14583. texture.onLoadedObservable.remove(onLoadObserver);
  14584. }
  14585. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14586. if (isKTX) {
  14587. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14588. }
  14589. else if (BABYLON.Tools.UseFallbackTexture) {
  14590. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14591. }
  14592. if (onError) {
  14593. onError(message || "Unknown error", exception);
  14594. }
  14595. };
  14596. var callback = null;
  14597. // processing for non-image formats
  14598. if (isKTX || isTGA || isDDS) {
  14599. if (isKTX) {
  14600. callback = function (data) {
  14601. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14602. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14603. ktx.uploadLevels(_this._gl, !noMipmap);
  14604. return false;
  14605. }, samplingMode);
  14606. };
  14607. }
  14608. else if (isTGA) {
  14609. callback = function (arrayBuffer) {
  14610. var data = new Uint8Array(arrayBuffer);
  14611. var header = BABYLON.TGATools.GetTGAHeader(data);
  14612. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14613. BABYLON.TGATools.UploadContent(_this._gl, data);
  14614. return false;
  14615. }, samplingMode);
  14616. };
  14617. }
  14618. else if (isDDS) {
  14619. callback = function (data) {
  14620. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14621. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14622. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14624. return false;
  14625. }, samplingMode);
  14626. };
  14627. }
  14628. if (!buffer) {
  14629. this._loadFile(url, function (data) {
  14630. if (callback) {
  14631. callback(data);
  14632. }
  14633. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14634. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14635. });
  14636. }
  14637. else {
  14638. if (callback) {
  14639. callback(buffer);
  14640. }
  14641. }
  14642. // image format processing
  14643. }
  14644. else {
  14645. var onload = function (img) {
  14646. if (fromBlob && !_this._doNotHandleContextLost) {
  14647. // We need to store the image if we need to rebuild the texture
  14648. // in case of a webgl context lost
  14649. texture._buffer = img;
  14650. }
  14651. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14652. var gl = _this._gl;
  14653. var isPot = (img.width === potWidth && img.height === potHeight);
  14654. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14655. if (isPot) {
  14656. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14657. return false;
  14658. }
  14659. // Using shaders to rescale because canvas.drawImage is lossy
  14660. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14661. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14662. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14665. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14667. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14668. _this._releaseTexture(source);
  14669. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14670. continuationCallback();
  14671. });
  14672. return true;
  14673. }, samplingMode);
  14674. };
  14675. if (!fromData || isBase64) {
  14676. if (buffer instanceof HTMLImageElement) {
  14677. onload(buffer);
  14678. }
  14679. else {
  14680. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14681. }
  14682. }
  14683. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14684. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14685. }
  14686. else {
  14687. onload(buffer);
  14688. }
  14689. }
  14690. return texture;
  14691. };
  14692. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14693. var _this = this;
  14694. var rtt = this.createRenderTargetTexture({
  14695. width: destination.width,
  14696. height: destination.height,
  14697. }, {
  14698. generateMipMaps: false,
  14699. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14700. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14701. generateDepthBuffer: false,
  14702. generateStencilBuffer: false
  14703. });
  14704. if (!this._rescalePostProcess) {
  14705. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14706. }
  14707. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14708. _this._rescalePostProcess.onApply = function (effect) {
  14709. effect._bindTexture("textureSampler", source);
  14710. };
  14711. var hostingScene = scene;
  14712. if (!hostingScene) {
  14713. hostingScene = _this.scenes[_this.scenes.length - 1];
  14714. }
  14715. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14716. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14717. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14718. _this.unBindFramebuffer(rtt);
  14719. _this._releaseTexture(rtt);
  14720. if (onComplete) {
  14721. onComplete();
  14722. }
  14723. });
  14724. };
  14725. /**
  14726. * Update a raw texture
  14727. * @param texture defines the texture to update
  14728. * @param data defines the data to store in the texture
  14729. * @param format defines the format of the data
  14730. * @param invertY defines if data must be stored with Y axis inverted
  14731. * @param compression defines the compression used (null by default)
  14732. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14733. */
  14734. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14735. if (compression === void 0) { compression = null; }
  14736. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14737. if (!texture) {
  14738. return;
  14739. }
  14740. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14741. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14742. // babylon's internalFormat but gl's texImage2D format
  14743. var internalFormat = this._getInternalFormat(format);
  14744. var textureType = this._getWebGLTextureType(type);
  14745. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14746. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14747. if (!this._doNotHandleContextLost) {
  14748. texture._bufferView = data;
  14749. texture.format = format;
  14750. texture.type = type;
  14751. texture.invertY = invertY;
  14752. texture._compression = compression;
  14753. }
  14754. if (texture.width % 4 !== 0) {
  14755. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14756. }
  14757. if (compression && data) {
  14758. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14759. }
  14760. else {
  14761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14762. }
  14763. if (texture.generateMipMaps) {
  14764. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14765. }
  14766. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14767. // this.resetTextureCache();
  14768. texture.isReady = true;
  14769. };
  14770. /**
  14771. * Creates a raw texture
  14772. * @param data defines the data to store in the texture
  14773. * @param width defines the width of the texture
  14774. * @param height defines the height of the texture
  14775. * @param format defines the format of the data
  14776. * @param generateMipMaps defines if the engine should generate the mip levels
  14777. * @param invertY defines if data must be stored with Y axis inverted
  14778. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14779. * @param compression defines the compression used (null by default)
  14780. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14781. * @returns the raw texture inside an InternalTexture
  14782. */
  14783. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14784. if (compression === void 0) { compression = null; }
  14785. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14786. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14787. texture.baseWidth = width;
  14788. texture.baseHeight = height;
  14789. texture.width = width;
  14790. texture.height = height;
  14791. texture.format = format;
  14792. texture.generateMipMaps = generateMipMaps;
  14793. texture.samplingMode = samplingMode;
  14794. texture.invertY = invertY;
  14795. texture._compression = compression;
  14796. texture.type = type;
  14797. if (!this._doNotHandleContextLost) {
  14798. texture._bufferView = data;
  14799. }
  14800. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14801. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14802. // Filters
  14803. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14806. if (generateMipMaps) {
  14807. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14808. }
  14809. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14810. this._internalTexturesCache.push(texture);
  14811. return texture;
  14812. };
  14813. /**
  14814. * Creates a dynamic texture
  14815. * @param width defines the width of the texture
  14816. * @param height defines the height of the texture
  14817. * @param generateMipMaps defines if the engine should generate the mip levels
  14818. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14819. * @returns the dynamic texture inside an InternalTexture
  14820. */
  14821. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14822. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14823. texture.baseWidth = width;
  14824. texture.baseHeight = height;
  14825. if (generateMipMaps) {
  14826. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14827. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14828. }
  14829. // this.resetTextureCache();
  14830. texture.width = width;
  14831. texture.height = height;
  14832. texture.isReady = false;
  14833. texture.generateMipMaps = generateMipMaps;
  14834. texture.samplingMode = samplingMode;
  14835. this.updateTextureSamplingMode(samplingMode, texture);
  14836. this._internalTexturesCache.push(texture);
  14837. return texture;
  14838. };
  14839. /**
  14840. * Update the sampling mode of a given texture
  14841. * @param samplingMode defines the required sampling mode
  14842. * @param texture defines the texture to update
  14843. */
  14844. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14845. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14846. if (texture.isCube) {
  14847. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14850. }
  14851. else if (texture.is3D) {
  14852. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14853. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14854. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14855. }
  14856. else {
  14857. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14858. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14859. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14860. }
  14861. texture.samplingMode = samplingMode;
  14862. };
  14863. /**
  14864. * Update the content of a dynamic texture
  14865. * @param texture defines the texture to update
  14866. * @param canvas defines the canvas containing the source
  14867. * @param invertY defines if data must be stored with Y axis inverted
  14868. * @param premulAlpha defines if alpha is stored as premultiplied
  14869. * @param format defines the format of the data
  14870. */
  14871. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14872. if (premulAlpha === void 0) { premulAlpha = false; }
  14873. if (!texture) {
  14874. return;
  14875. }
  14876. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14877. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14878. if (premulAlpha) {
  14879. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14880. }
  14881. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14882. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14883. if (texture.generateMipMaps) {
  14884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14885. }
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14887. if (premulAlpha) {
  14888. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14889. }
  14890. texture.isReady = true;
  14891. };
  14892. /**
  14893. * Update a video texture
  14894. * @param texture defines the texture to update
  14895. * @param video defines the video element to use
  14896. * @param invertY defines if data must be stored with Y axis inverted
  14897. */
  14898. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14899. if (!texture || texture._isDisabled) {
  14900. return;
  14901. }
  14902. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14903. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14904. try {
  14905. // Testing video texture support
  14906. if (this._videoTextureSupported === undefined) {
  14907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14908. if (this._gl.getError() !== 0) {
  14909. this._videoTextureSupported = false;
  14910. }
  14911. else {
  14912. this._videoTextureSupported = true;
  14913. }
  14914. }
  14915. // Copy video through the current working canvas if video texture is not supported
  14916. if (!this._videoTextureSupported) {
  14917. if (!texture._workingCanvas) {
  14918. texture._workingCanvas = document.createElement("canvas");
  14919. var context = texture._workingCanvas.getContext("2d");
  14920. if (!context) {
  14921. throw new Error("Unable to get 2d context");
  14922. }
  14923. texture._workingContext = context;
  14924. texture._workingCanvas.width = texture.width;
  14925. texture._workingCanvas.height = texture.height;
  14926. }
  14927. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14928. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14929. }
  14930. else {
  14931. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14932. }
  14933. if (texture.generateMipMaps) {
  14934. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14935. }
  14936. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14937. // this.resetTextureCache();
  14938. texture.isReady = true;
  14939. }
  14940. catch (ex) {
  14941. // Something unexpected
  14942. // Let's disable the texture
  14943. texture._isDisabled = true;
  14944. }
  14945. };
  14946. /**
  14947. * Updates a depth texture Comparison Mode and Function.
  14948. * If the comparison Function is equal to 0, the mode will be set to none.
  14949. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14950. * @param texture The texture to set the comparison function for
  14951. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14952. */
  14953. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14954. if (this.webGLVersion === 1) {
  14955. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14956. return;
  14957. }
  14958. var gl = this._gl;
  14959. if (texture.isCube) {
  14960. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14961. if (comparisonFunction === 0) {
  14962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14964. }
  14965. else {
  14966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14970. }
  14971. else {
  14972. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14973. if (comparisonFunction === 0) {
  14974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14976. }
  14977. else {
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14982. }
  14983. texture._comparisonFunction = comparisonFunction;
  14984. };
  14985. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14986. var width = size.width || size;
  14987. var height = size.height || size;
  14988. internalTexture.baseWidth = width;
  14989. internalTexture.baseHeight = height;
  14990. internalTexture.width = width;
  14991. internalTexture.height = height;
  14992. internalTexture.isReady = true;
  14993. internalTexture.samples = 1;
  14994. internalTexture.generateMipMaps = false;
  14995. internalTexture._generateDepthBuffer = true;
  14996. internalTexture._generateStencilBuffer = generateStencil;
  14997. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14998. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14999. internalTexture._comparisonFunction = comparisonFunction;
  15000. var gl = this._gl;
  15001. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15002. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15003. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15004. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15005. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15007. if (comparisonFunction === 0) {
  15008. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15010. }
  15011. else {
  15012. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15014. }
  15015. };
  15016. /**
  15017. * Creates a depth stencil texture.
  15018. * This is only available in WebGL 2 or with the depth texture extension available.
  15019. * @param size The size of face edge in the texture.
  15020. * @param options The options defining the texture.
  15021. * @returns The texture
  15022. */
  15023. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15024. if (options.isCube) {
  15025. var width = size.width || size;
  15026. return this._createDepthStencilCubeTexture(width, options);
  15027. }
  15028. else {
  15029. return this._createDepthStencilTexture(size, options);
  15030. }
  15031. };
  15032. /**
  15033. * Creates a depth stencil texture.
  15034. * This is only available in WebGL 2 or with the depth texture extension available.
  15035. * @param size The size of face edge in the texture.
  15036. * @param options The options defining the texture.
  15037. * @returns The texture
  15038. */
  15039. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15040. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15041. if (!this._caps.depthTextureExtension) {
  15042. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15043. return internalTexture;
  15044. }
  15045. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15046. var gl = this._gl;
  15047. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15048. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15049. if (this.webGLVersion > 1) {
  15050. if (internalOptions.generateStencil) {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15052. }
  15053. else {
  15054. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15055. }
  15056. }
  15057. else {
  15058. if (internalOptions.generateStencil) {
  15059. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Creates a depth stencil cube texture.
  15070. * This is only available in WebGL 2.
  15071. * @param size The size of face edge in the cube texture.
  15072. * @param options The options defining the cube texture.
  15073. * @returns The cube texture
  15074. */
  15075. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15076. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15077. internalTexture.isCube = true;
  15078. if (this.webGLVersion === 1) {
  15079. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15080. return internalTexture;
  15081. }
  15082. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15083. var gl = this._gl;
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15085. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15086. // Create the depth/stencil buffer
  15087. for (var face = 0; face < 6; face++) {
  15088. if (internalOptions.generateStencil) {
  15089. 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);
  15090. }
  15091. else {
  15092. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15093. }
  15094. }
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15096. return internalTexture;
  15097. };
  15098. /**
  15099. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15100. * @param renderTarget The render target to set the frame buffer for
  15101. */
  15102. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15103. // Create the framebuffer
  15104. var internalTexture = renderTarget.getInternalTexture();
  15105. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15106. return;
  15107. }
  15108. var gl = this._gl;
  15109. var depthStencilTexture = renderTarget.depthStencilTexture;
  15110. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15111. if (depthStencilTexture.isCube) {
  15112. if (depthStencilTexture._generateStencilBuffer) {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. else {
  15116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15117. }
  15118. }
  15119. else {
  15120. if (depthStencilTexture._generateStencilBuffer) {
  15121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15122. }
  15123. else {
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15125. }
  15126. }
  15127. this.bindUnboundFramebuffer(null);
  15128. };
  15129. /**
  15130. * Creates a new render target texture
  15131. * @param size defines the size of the texture
  15132. * @param options defines the options used to create the texture
  15133. * @returns a new render target texture stored in an InternalTexture
  15134. */
  15135. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15136. var fullOptions = new RenderTargetCreationOptions();
  15137. if (options !== undefined && typeof options === "object") {
  15138. fullOptions.generateMipMaps = options.generateMipMaps;
  15139. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15140. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15141. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15142. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15143. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15144. }
  15145. else {
  15146. fullOptions.generateMipMaps = options;
  15147. fullOptions.generateDepthBuffer = true;
  15148. fullOptions.generateStencilBuffer = false;
  15149. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15150. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15151. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15152. }
  15153. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15154. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15155. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15156. }
  15157. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15158. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15159. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15160. }
  15161. var gl = this._gl;
  15162. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15163. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15164. var width = size.width || size;
  15165. var height = size.height || size;
  15166. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15167. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15168. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15169. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15170. }
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15176. // Create the framebuffer
  15177. var currentFrameBuffer = this._currentFramebuffer;
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(currentFrameBuffer);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15200. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15201. // this.resetTextureCache();
  15202. this._internalTexturesCache.push(texture);
  15203. return texture;
  15204. };
  15205. /**
  15206. * Create a multi render target texture
  15207. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15208. * @param size defines the size of the texture
  15209. * @param options defines the creation options
  15210. * @returns the cube texture as an InternalTexture
  15211. */
  15212. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15213. var generateMipMaps = false;
  15214. var generateDepthBuffer = true;
  15215. var generateStencilBuffer = false;
  15216. var generateDepthTexture = false;
  15217. var textureCount = 1;
  15218. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15220. var types = new Array();
  15221. var samplingModes = new Array();
  15222. if (options !== undefined) {
  15223. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15225. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15226. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15227. textureCount = options.textureCount || 1;
  15228. if (options.types) {
  15229. types = options.types;
  15230. }
  15231. if (options.samplingModes) {
  15232. samplingModes = options.samplingModes;
  15233. }
  15234. }
  15235. var gl = this._gl;
  15236. // Create the framebuffer
  15237. var framebuffer = gl.createFramebuffer();
  15238. this.bindUnboundFramebuffer(framebuffer);
  15239. var width = size.width || size;
  15240. var height = size.height || size;
  15241. var textures = [];
  15242. var attachments = [];
  15243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15244. for (var i = 0; i < textureCount; i++) {
  15245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15246. var type = types[i] || defaultType;
  15247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15249. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15250. }
  15251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15253. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15254. }
  15255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15259. }
  15260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15262. textures.push(texture);
  15263. attachments.push(attachment);
  15264. gl.activeTexture(gl["TEXTURE" + i]);
  15265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15272. if (generateMipMaps) {
  15273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15274. }
  15275. // Unbind
  15276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15277. texture._framebuffer = framebuffer;
  15278. texture._depthStencilBuffer = depthStencilBuffer;
  15279. texture.baseWidth = width;
  15280. texture.baseHeight = height;
  15281. texture.width = width;
  15282. texture.height = height;
  15283. texture.isReady = true;
  15284. texture.samples = 1;
  15285. texture.generateMipMaps = generateMipMaps;
  15286. texture.samplingMode = samplingMode;
  15287. texture.type = type;
  15288. texture._generateDepthBuffer = generateDepthBuffer;
  15289. texture._generateStencilBuffer = generateStencilBuffer;
  15290. texture._attachments = attachments;
  15291. this._internalTexturesCache.push(texture);
  15292. }
  15293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15294. // Depth texture
  15295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15296. gl.activeTexture(gl.TEXTURE0);
  15297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15302. 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);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15304. depthTexture._framebuffer = framebuffer;
  15305. depthTexture.baseWidth = width;
  15306. depthTexture.baseHeight = height;
  15307. depthTexture.width = width;
  15308. depthTexture.height = height;
  15309. depthTexture.isReady = true;
  15310. depthTexture.samples = 1;
  15311. depthTexture.generateMipMaps = generateMipMaps;
  15312. depthTexture.samplingMode = gl.NEAREST;
  15313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15315. textures.push(depthTexture);
  15316. this._internalTexturesCache.push(depthTexture);
  15317. }
  15318. gl.drawBuffers(attachments);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. this.resetTextureCache();
  15322. return textures;
  15323. };
  15324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15325. if (samples === void 0) { samples = 1; }
  15326. var depthStencilBuffer = null;
  15327. var gl = this._gl;
  15328. // Create the depth/stencil buffer
  15329. if (generateStencilBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. else if (generateDepthBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. return depthStencilBuffer;
  15352. };
  15353. /**
  15354. * Updates the sample count of a render target texture
  15355. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15356. * @param texture defines the texture to update
  15357. * @param samples defines the sample count to set
  15358. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15359. */
  15360. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15361. if (this.webGLVersion < 2 || !texture) {
  15362. return 1;
  15363. }
  15364. if (texture.samples === samples) {
  15365. return samples;
  15366. }
  15367. var gl = this._gl;
  15368. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15369. // Dispose previous render buffers
  15370. if (texture._depthStencilBuffer) {
  15371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15372. texture._depthStencilBuffer = null;
  15373. }
  15374. if (texture._MSAAFramebuffer) {
  15375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15376. texture._MSAAFramebuffer = null;
  15377. }
  15378. if (texture._MSAARenderBuffer) {
  15379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15380. texture._MSAARenderBuffer = null;
  15381. }
  15382. if (samples > 1) {
  15383. var framebuffer = gl.createFramebuffer();
  15384. if (!framebuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. texture._MSAAFramebuffer = framebuffer;
  15388. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAARenderBuffer = colorRenderbuffer;
  15397. }
  15398. else {
  15399. this.bindUnboundFramebuffer(texture._framebuffer);
  15400. }
  15401. texture.samples = samples;
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15404. this.bindUnboundFramebuffer(null);
  15405. return samples;
  15406. };
  15407. /**
  15408. * Update the sample count for a given multiple render target texture
  15409. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15410. * @param textures defines the textures to update
  15411. * @param samples defines the sample count to set
  15412. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15413. */
  15414. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15415. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15416. return 1;
  15417. }
  15418. if (textures[0].samples === samples) {
  15419. return samples;
  15420. }
  15421. var gl = this._gl;
  15422. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15423. // Dispose previous render buffers
  15424. if (textures[0]._depthStencilBuffer) {
  15425. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15426. textures[0]._depthStencilBuffer = null;
  15427. }
  15428. if (textures[0]._MSAAFramebuffer) {
  15429. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15430. textures[0]._MSAAFramebuffer = null;
  15431. }
  15432. for (var i = 0; i < textures.length; i++) {
  15433. if (textures[i]._MSAARenderBuffer) {
  15434. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15435. textures[i]._MSAARenderBuffer = null;
  15436. }
  15437. }
  15438. if (samples > 1) {
  15439. var framebuffer = gl.createFramebuffer();
  15440. if (!framebuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. this.bindUnboundFramebuffer(framebuffer);
  15444. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15445. var attachments = [];
  15446. for (var i = 0; i < textures.length; i++) {
  15447. var texture = textures[i];
  15448. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15449. var colorRenderbuffer = gl.createRenderbuffer();
  15450. if (!colorRenderbuffer) {
  15451. throw new Error("Unable to create multi sampled framebuffer");
  15452. }
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15456. texture._MSAAFramebuffer = framebuffer;
  15457. texture._MSAARenderBuffer = colorRenderbuffer;
  15458. texture.samples = samples;
  15459. texture._depthStencilBuffer = depthStencilBuffer;
  15460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15461. attachments.push(attachment);
  15462. }
  15463. gl.drawBuffers(attachments);
  15464. }
  15465. else {
  15466. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15467. }
  15468. this.bindUnboundFramebuffer(null);
  15469. return samples;
  15470. };
  15471. /** @hidden */
  15472. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15473. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15474. };
  15475. /** @hidden */
  15476. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15477. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15478. };
  15479. /** @hidden */
  15480. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15481. var gl = this._gl;
  15482. var textureType = this._getWebGLTextureType(texture.type);
  15483. var format = this._getInternalFormat(texture.format);
  15484. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15485. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15486. this._bindTextureDirectly(bindTarget, texture, true);
  15487. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15488. var target = gl.TEXTURE_2D;
  15489. if (texture.isCube) {
  15490. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15491. }
  15492. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15493. this._bindTextureDirectly(bindTarget, null, true);
  15494. };
  15495. /**
  15496. * Creates a new render target cube texture
  15497. * @param size defines the size of the texture
  15498. * @param options defines the options used to create the texture
  15499. * @returns a new render target cube texture stored in an InternalTexture
  15500. */
  15501. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15502. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15503. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15504. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15505. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15506. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15507. }
  15508. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15509. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15510. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15511. }
  15512. var gl = this._gl;
  15513. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15514. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15515. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15516. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15517. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15518. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15519. }
  15520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15524. for (var face = 0; face < 6; face++) {
  15525. 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);
  15526. }
  15527. // Create the framebuffer
  15528. var framebuffer = gl.createFramebuffer();
  15529. this.bindUnboundFramebuffer(framebuffer);
  15530. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15531. // MipMaps
  15532. if (fullOptions.generateMipMaps) {
  15533. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15534. }
  15535. // Unbind
  15536. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15537. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15538. this.bindUnboundFramebuffer(null);
  15539. texture._framebuffer = framebuffer;
  15540. texture.width = size;
  15541. texture.height = size;
  15542. texture.isReady = true;
  15543. texture.isCube = true;
  15544. texture.samples = 1;
  15545. texture.generateMipMaps = fullOptions.generateMipMaps;
  15546. texture.samplingMode = fullOptions.samplingMode;
  15547. texture.type = fullOptions.type;
  15548. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15549. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15550. this._internalTexturesCache.push(texture);
  15551. return texture;
  15552. };
  15553. /**
  15554. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15555. * @param rootUrl defines the url where the file to load is located
  15556. * @param scene defines the current scene
  15557. * @param lodScale defines scale to apply to the mip map selection
  15558. * @param lodOffset defines offset to apply to the mip map selection
  15559. * @param onLoad defines an optional callback raised when the texture is loaded
  15560. * @param onError defines an optional callback raised if there is an issue to load the texture
  15561. * @param format defines the format of the data
  15562. * @param forcedExtension defines the extension to use to pick the right loader
  15563. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15564. * @returns the cube texture as an InternalTexture
  15565. */
  15566. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15567. var _this = this;
  15568. if (onLoad === void 0) { onLoad = null; }
  15569. if (onError === void 0) { onError = null; }
  15570. if (forcedExtension === void 0) { forcedExtension = null; }
  15571. if (createPolynomials === void 0) { createPolynomials = true; }
  15572. var callback = function (loadData) {
  15573. if (!loadData) {
  15574. if (onLoad) {
  15575. onLoad(null);
  15576. }
  15577. return;
  15578. }
  15579. var texture = loadData.texture;
  15580. if (!createPolynomials) {
  15581. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15582. }
  15583. else if (loadData.info.sphericalPolynomial) {
  15584. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15585. }
  15586. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15587. if (_this._caps.textureLOD) {
  15588. // Do not add extra process if texture lod is supported.
  15589. if (onLoad) {
  15590. onLoad(texture);
  15591. }
  15592. return;
  15593. }
  15594. var mipSlices = 3;
  15595. var gl = _this._gl;
  15596. var width = loadData.width;
  15597. if (!width) {
  15598. return;
  15599. }
  15600. var textures = [];
  15601. for (var i = 0; i < mipSlices; i++) {
  15602. //compute LOD from even spacing in smoothness (matching shader calculation)
  15603. var smoothness = i / (mipSlices - 1);
  15604. var roughness = 1 - smoothness;
  15605. var minLODIndex = lodOffset; // roughness = 0
  15606. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15607. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15608. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15609. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15610. glTextureFromLod.isCube = true;
  15611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15616. if (loadData.isDDS) {
  15617. var info = loadData.info;
  15618. var data = loadData.data;
  15619. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15620. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15621. }
  15622. else {
  15623. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15624. }
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15626. // Wrap in a base texture for easy binding.
  15627. var lodTexture = new BABYLON.BaseTexture(scene);
  15628. lodTexture.isCube = true;
  15629. lodTexture._texture = glTextureFromLod;
  15630. glTextureFromLod.isReady = true;
  15631. textures.push(lodTexture);
  15632. }
  15633. texture._lodTextureHigh = textures[2];
  15634. texture._lodTextureMid = textures[1];
  15635. texture._lodTextureLow = textures[0];
  15636. if (onLoad) {
  15637. onLoad(texture);
  15638. }
  15639. };
  15640. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15641. };
  15642. /**
  15643. * Creates a cube texture
  15644. * @param rootUrl defines the url where the files to load is located
  15645. * @param scene defines the current scene
  15646. * @param files defines the list of files to load (1 per face)
  15647. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15648. * @param onLoad defines an optional callback raised when the texture is loaded
  15649. * @param onError defines an optional callback raised if there is an issue to load the texture
  15650. * @param format defines the format of the data
  15651. * @param forcedExtension defines the extension to use to pick the right loader
  15652. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15653. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15654. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15655. * @returns the cube texture as an InternalTexture
  15656. */
  15657. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15658. var _this = this;
  15659. if (onLoad === void 0) { onLoad = null; }
  15660. if (onError === void 0) { onError = null; }
  15661. if (forcedExtension === void 0) { forcedExtension = null; }
  15662. if (createPolynomials === void 0) { createPolynomials = false; }
  15663. if (lodScale === void 0) { lodScale = 0; }
  15664. if (lodOffset === void 0) { lodOffset = 0; }
  15665. var gl = this._gl;
  15666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15667. texture.isCube = true;
  15668. texture.url = rootUrl;
  15669. texture.generateMipMaps = !noMipmap;
  15670. texture._lodGenerationScale = lodScale;
  15671. texture._lodGenerationOffset = lodOffset;
  15672. if (!this._doNotHandleContextLost) {
  15673. texture._extension = forcedExtension;
  15674. texture._files = files;
  15675. }
  15676. var isKTX = false;
  15677. var isDDS = false;
  15678. var isEnv = false;
  15679. var lastDot = rootUrl.lastIndexOf('.');
  15680. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15681. if (this._textureFormatInUse) {
  15682. extension = this._textureFormatInUse;
  15683. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15684. isKTX = true;
  15685. }
  15686. else {
  15687. isDDS = (extension === ".dds");
  15688. isEnv = (extension === ".env");
  15689. }
  15690. var onerror = function (request, exception) {
  15691. if (onError && request) {
  15692. onError(request.status + " " + request.statusText, exception);
  15693. }
  15694. };
  15695. if (isKTX) {
  15696. this._loadFile(rootUrl, function (data) {
  15697. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15698. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15699. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15700. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15701. ktx.uploadLevels(_this._gl, !noMipmap);
  15702. _this.setCubeMapTextureParams(gl, loadMipmap);
  15703. texture.width = ktx.pixelWidth;
  15704. texture.height = ktx.pixelHeight;
  15705. texture.isReady = true;
  15706. }, undefined, undefined, true, onerror);
  15707. }
  15708. else if (isEnv) {
  15709. this._loadFile(rootUrl, function (data) {
  15710. data = data;
  15711. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15712. if (info) {
  15713. texture.width = info.width;
  15714. texture.height = info.width;
  15715. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15716. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15717. texture.isReady = true;
  15718. if (onLoad) {
  15719. onLoad();
  15720. }
  15721. });
  15722. }
  15723. else if (onError) {
  15724. onError("Can not parse the environment file", null);
  15725. }
  15726. }, undefined, undefined, true, onerror);
  15727. }
  15728. else if (isDDS) {
  15729. if (files && files.length === 6) {
  15730. this._cascadeLoadFiles(scene, function (imgs) {
  15731. var info;
  15732. var loadMipmap = false;
  15733. var width = 0;
  15734. for (var index = 0; index < imgs.length; index++) {
  15735. var data = imgs[index];
  15736. info = BABYLON.DDSTools.GetDDSInfo(data);
  15737. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15740. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15741. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15743. }
  15744. texture.width = info.width;
  15745. texture.height = info.height;
  15746. texture.type = info.textureType;
  15747. width = info.width;
  15748. }
  15749. _this.setCubeMapTextureParams(gl, loadMipmap);
  15750. texture.isReady = true;
  15751. if (onLoad) {
  15752. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15753. }
  15754. }, files, onError);
  15755. }
  15756. else {
  15757. this._loadFile(rootUrl, function (data) {
  15758. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15759. if (createPolynomials) {
  15760. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15761. }
  15762. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15765. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15766. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15767. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15768. }
  15769. _this.setCubeMapTextureParams(gl, loadMipmap);
  15770. texture.width = info.width;
  15771. texture.height = info.height;
  15772. texture.isReady = true;
  15773. texture.type = info.textureType;
  15774. if (onLoad) {
  15775. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15776. }
  15777. }, undefined, undefined, true, onerror);
  15778. }
  15779. }
  15780. else {
  15781. if (!files) {
  15782. throw new Error("Cannot load cubemap because files were not defined");
  15783. }
  15784. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15785. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15786. var height = width;
  15787. _this._prepareWorkingCanvas();
  15788. if (!_this._workingCanvas || !_this._workingContext) {
  15789. return;
  15790. }
  15791. _this._workingCanvas.width = width;
  15792. _this._workingCanvas.height = height;
  15793. var faces = [
  15794. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15795. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15796. ];
  15797. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15798. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15799. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15800. for (var index = 0; index < faces.length; index++) {
  15801. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15802. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15803. }
  15804. if (!noMipmap) {
  15805. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15806. }
  15807. _this.setCubeMapTextureParams(gl, !noMipmap);
  15808. texture.width = width;
  15809. texture.height = height;
  15810. texture.isReady = true;
  15811. if (format) {
  15812. texture.format = format;
  15813. }
  15814. texture.onLoadedObservable.notifyObservers(texture);
  15815. texture.onLoadedObservable.clear();
  15816. if (onLoad) {
  15817. onLoad();
  15818. }
  15819. }, files, onError);
  15820. }
  15821. this._internalTexturesCache.push(texture);
  15822. return texture;
  15823. };
  15824. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15829. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15830. // this.resetTextureCache();
  15831. };
  15832. /**
  15833. * Update a raw cube texture
  15834. * @param texture defines the texture to udpdate
  15835. * @param data defines the data to store
  15836. * @param format defines the data format
  15837. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15838. * @param invertY defines if data must be stored with Y axis inverted
  15839. * @param compression defines the compression used (null by default)
  15840. * @param level defines which level of the texture to update
  15841. */
  15842. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15843. if (compression === void 0) { compression = null; }
  15844. if (level === void 0) { level = 0; }
  15845. texture._bufferViewArray = data;
  15846. texture.format = format;
  15847. texture.type = type;
  15848. texture.invertY = invertY;
  15849. texture._compression = compression;
  15850. var gl = this._gl;
  15851. var textureType = this._getWebGLTextureType(type);
  15852. var internalFormat = this._getInternalFormat(format);
  15853. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15854. var needConversion = false;
  15855. if (internalFormat === gl.RGB) {
  15856. internalFormat = gl.RGBA;
  15857. needConversion = true;
  15858. }
  15859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15860. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15861. if (texture.width % 4 !== 0) {
  15862. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15863. }
  15864. // Data are known to be in +X +Y +Z -X -Y -Z
  15865. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15866. var faceData = data[faceIndex];
  15867. if (compression) {
  15868. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15869. }
  15870. else {
  15871. if (needConversion) {
  15872. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15873. }
  15874. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15875. }
  15876. }
  15877. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15878. if (isPot && texture.generateMipMaps && level === 0) {
  15879. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15880. }
  15881. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15882. // this.resetTextureCache();
  15883. texture.isReady = true;
  15884. };
  15885. /**
  15886. * Creates a new raw cube texture
  15887. * @param data defines the array of data to use to create each face
  15888. * @param size defines the size of the textures
  15889. * @param format defines the format of the data
  15890. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15891. * @param generateMipMaps defines if the engine should generate the mip levels
  15892. * @param invertY defines if data must be stored with Y axis inverted
  15893. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15894. * @param compression defines the compression used (null by default)
  15895. * @returns the cube texture as an InternalTexture
  15896. */
  15897. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15898. if (compression === void 0) { compression = null; }
  15899. var gl = this._gl;
  15900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15901. texture.isCube = true;
  15902. texture.generateMipMaps = generateMipMaps;
  15903. texture.format = format;
  15904. texture.type = type;
  15905. if (!this._doNotHandleContextLost) {
  15906. texture._bufferViewArray = data;
  15907. }
  15908. var textureType = this._getWebGLTextureType(type);
  15909. var internalFormat = this._getInternalFormat(format);
  15910. if (internalFormat === gl.RGB) {
  15911. internalFormat = gl.RGBA;
  15912. }
  15913. var width = size;
  15914. var height = width;
  15915. texture.width = width;
  15916. texture.height = height;
  15917. // Double check on POT to generate Mips.
  15918. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15919. if (!isPot) {
  15920. generateMipMaps = false;
  15921. }
  15922. // Upload data if needed. The texture won't be ready until then.
  15923. if (data) {
  15924. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15925. }
  15926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15927. // Filters
  15928. if (data && generateMipMaps) {
  15929. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15930. }
  15931. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15934. }
  15935. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15938. }
  15939. else {
  15940. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15943. }
  15944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15946. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15947. return texture;
  15948. };
  15949. /**
  15950. * Creates a new raw cube texture from a specified url
  15951. * @param url defines the url where the data is located
  15952. * @param scene defines the current scene
  15953. * @param size defines the size of the textures
  15954. * @param format defines the format of the data
  15955. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15956. * @param noMipmap defines if the engine should avoid generating the mip levels
  15957. * @param callback defines a callback used to extract texture data from loaded data
  15958. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15959. * @param onLoad defines a callback called when texture is loaded
  15960. * @param onError defines a callback called if there is an error
  15961. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15962. * @param invertY defines if data must be stored with Y axis inverted
  15963. * @returns the cube texture as an InternalTexture
  15964. */
  15965. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15966. var _this = this;
  15967. if (onLoad === void 0) { onLoad = null; }
  15968. if (onError === void 0) { onError = null; }
  15969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15970. if (invertY === void 0) { invertY = false; }
  15971. var gl = this._gl;
  15972. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15973. scene._addPendingData(texture);
  15974. texture.url = url;
  15975. this._internalTexturesCache.push(texture);
  15976. var onerror = function (request, exception) {
  15977. scene._removePendingData(texture);
  15978. if (onError && request) {
  15979. onError(request.status + " " + request.statusText, exception);
  15980. }
  15981. };
  15982. var internalCallback = function (data) {
  15983. var width = texture.width;
  15984. var faceDataArrays = callback(data);
  15985. if (!faceDataArrays) {
  15986. return;
  15987. }
  15988. if (mipmapGenerator) {
  15989. var textureType = _this._getWebGLTextureType(type);
  15990. var internalFormat = _this._getInternalFormat(format);
  15991. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15992. var needConversion = false;
  15993. if (internalFormat === gl.RGB) {
  15994. internalFormat = gl.RGBA;
  15995. needConversion = true;
  15996. }
  15997. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15998. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15999. var mipData = mipmapGenerator(faceDataArrays);
  16000. for (var level = 0; level < mipData.length; level++) {
  16001. var mipSize = width >> level;
  16002. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16003. var mipFaceData = mipData[level][faceIndex];
  16004. if (needConversion) {
  16005. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16006. }
  16007. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16008. }
  16009. }
  16010. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16011. }
  16012. else {
  16013. texture.generateMipMaps = !noMipmap;
  16014. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16015. }
  16016. texture.isReady = true;
  16017. // this.resetTextureCache();
  16018. scene._removePendingData(texture);
  16019. if (onLoad) {
  16020. onLoad();
  16021. }
  16022. };
  16023. this._loadFile(url, function (data) {
  16024. internalCallback(data);
  16025. }, undefined, scene.database, true, onerror);
  16026. return texture;
  16027. };
  16028. ;
  16029. /**
  16030. * Update a raw 3D texture
  16031. * @param texture defines the texture to update
  16032. * @param data defines the data to store
  16033. * @param format defines the data format
  16034. * @param invertY defines if data must be stored with Y axis inverted
  16035. * @param compression defines the used compression (can be null)
  16036. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16037. */
  16038. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16039. if (compression === void 0) { compression = null; }
  16040. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16041. var internalType = this._getWebGLTextureType(textureType);
  16042. var internalFormat = this._getInternalFormat(format);
  16043. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16044. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16045. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16046. if (!this._doNotHandleContextLost) {
  16047. texture._bufferView = data;
  16048. texture.format = format;
  16049. texture.invertY = invertY;
  16050. texture._compression = compression;
  16051. }
  16052. if (texture.width % 4 !== 0) {
  16053. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16054. }
  16055. if (compression && data) {
  16056. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16057. }
  16058. else {
  16059. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16060. }
  16061. if (texture.generateMipMaps) {
  16062. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16063. }
  16064. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16065. // this.resetTextureCache();
  16066. texture.isReady = true;
  16067. };
  16068. /**
  16069. * Creates a new raw 3D texture
  16070. * @param data defines the data used to create the texture
  16071. * @param width defines the width of the texture
  16072. * @param height defines the height of the texture
  16073. * @param depth defines the depth of the texture
  16074. * @param format defines the format of the texture
  16075. * @param generateMipMaps defines if the engine must generate mip levels
  16076. * @param invertY defines if data must be stored with Y axis inverted
  16077. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16078. * @param compression defines the compressed used (can be null)
  16079. * @param textureType defines the compressed used (can be null)
  16080. * @returns a new raw 3D texture (stored in an InternalTexture)
  16081. */
  16082. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16083. if (compression === void 0) { compression = null; }
  16084. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16085. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16086. texture.baseWidth = width;
  16087. texture.baseHeight = height;
  16088. texture.baseDepth = depth;
  16089. texture.width = width;
  16090. texture.height = height;
  16091. texture.depth = depth;
  16092. texture.format = format;
  16093. texture.type = textureType;
  16094. texture.generateMipMaps = generateMipMaps;
  16095. texture.samplingMode = samplingMode;
  16096. texture.is3D = true;
  16097. if (!this._doNotHandleContextLost) {
  16098. texture._bufferView = data;
  16099. }
  16100. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16101. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16102. // Filters
  16103. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16104. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16105. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16106. if (generateMipMaps) {
  16107. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16108. }
  16109. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16110. this._internalTexturesCache.push(texture);
  16111. return texture;
  16112. };
  16113. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16114. var gl = this._gl;
  16115. if (!gl) {
  16116. return;
  16117. }
  16118. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16121. if (!noMipmap && !isCompressed) {
  16122. gl.generateMipmap(gl.TEXTURE_2D);
  16123. }
  16124. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16125. // this.resetTextureCache();
  16126. if (scene) {
  16127. scene._removePendingData(texture);
  16128. }
  16129. texture.onLoadedObservable.notifyObservers(texture);
  16130. texture.onLoadedObservable.clear();
  16131. };
  16132. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16133. var _this = this;
  16134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16135. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16136. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16137. var gl = this._gl;
  16138. if (!gl) {
  16139. return;
  16140. }
  16141. if (!texture._webGLTexture) {
  16142. // this.resetTextureCache();
  16143. if (scene) {
  16144. scene._removePendingData(texture);
  16145. }
  16146. return;
  16147. }
  16148. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16150. texture.baseWidth = width;
  16151. texture.baseHeight = height;
  16152. texture.width = potWidth;
  16153. texture.height = potHeight;
  16154. texture.isReady = true;
  16155. if (processFunction(potWidth, potHeight, function () {
  16156. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16157. })) {
  16158. // Returning as texture needs extra async steps
  16159. return;
  16160. }
  16161. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16162. };
  16163. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16164. // Create new RGBA data container.
  16165. var rgbaData;
  16166. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16167. rgbaData = new Float32Array(width * height * 4);
  16168. }
  16169. else {
  16170. rgbaData = new Uint32Array(width * height * 4);
  16171. }
  16172. // Convert each pixel.
  16173. for (var x = 0; x < width; x++) {
  16174. for (var y = 0; y < height; y++) {
  16175. var index = (y * width + x) * 3;
  16176. var newIndex = (y * width + x) * 4;
  16177. // Map Old Value to new value.
  16178. rgbaData[newIndex + 0] = rgbData[index + 0];
  16179. rgbaData[newIndex + 1] = rgbData[index + 1];
  16180. rgbaData[newIndex + 2] = rgbData[index + 2];
  16181. // Add fully opaque alpha channel.
  16182. rgbaData[newIndex + 3] = 1;
  16183. }
  16184. }
  16185. return rgbaData;
  16186. };
  16187. /** @hidden */
  16188. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16189. var gl = this._gl;
  16190. if (texture._framebuffer) {
  16191. gl.deleteFramebuffer(texture._framebuffer);
  16192. texture._framebuffer = null;
  16193. }
  16194. if (texture._depthStencilBuffer) {
  16195. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16196. texture._depthStencilBuffer = null;
  16197. }
  16198. if (texture._MSAAFramebuffer) {
  16199. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16200. texture._MSAAFramebuffer = null;
  16201. }
  16202. if (texture._MSAARenderBuffer) {
  16203. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16204. texture._MSAARenderBuffer = null;
  16205. }
  16206. };
  16207. /** @hidden */
  16208. Engine.prototype._releaseTexture = function (texture) {
  16209. var gl = this._gl;
  16210. this._releaseFramebufferObjects(texture);
  16211. gl.deleteTexture(texture._webGLTexture);
  16212. // Unbind channels
  16213. this.unbindAllTextures();
  16214. var index = this._internalTexturesCache.indexOf(texture);
  16215. if (index !== -1) {
  16216. this._internalTexturesCache.splice(index, 1);
  16217. }
  16218. // Integrated fixed lod samplers.
  16219. if (texture._lodTextureHigh) {
  16220. texture._lodTextureHigh.dispose();
  16221. }
  16222. if (texture._lodTextureMid) {
  16223. texture._lodTextureMid.dispose();
  16224. }
  16225. if (texture._lodTextureLow) {
  16226. texture._lodTextureLow.dispose();
  16227. }
  16228. // Set output texture of post process to null if the texture has been released/disposed
  16229. this.scenes.forEach(function (scene) {
  16230. scene.postProcesses.forEach(function (postProcess) {
  16231. if (postProcess._outputTexture == texture) {
  16232. postProcess._outputTexture = null;
  16233. }
  16234. });
  16235. scene.cameras.forEach(function (camera) {
  16236. camera._postProcesses.forEach(function (postProcess) {
  16237. if (postProcess) {
  16238. if (postProcess._outputTexture == texture) {
  16239. postProcess._outputTexture = null;
  16240. }
  16241. }
  16242. });
  16243. });
  16244. });
  16245. };
  16246. Engine.prototype.setProgram = function (program) {
  16247. if (this._currentProgram !== program) {
  16248. this._gl.useProgram(program);
  16249. this._currentProgram = program;
  16250. }
  16251. };
  16252. /**
  16253. * Binds an effect to the webGL context
  16254. * @param effect defines the effect to bind
  16255. */
  16256. Engine.prototype.bindSamplers = function (effect) {
  16257. this.setProgram(effect.getProgram());
  16258. var samplers = effect.getSamplers();
  16259. for (var index = 0; index < samplers.length; index++) {
  16260. var uniform = effect.getUniform(samplers[index]);
  16261. if (uniform) {
  16262. this._boundUniforms[index] = uniform;
  16263. }
  16264. }
  16265. this._currentEffect = null;
  16266. };
  16267. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16268. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16269. return;
  16270. }
  16271. // Remove
  16272. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16273. // Bind last to it
  16274. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16275. // Bind to dummy
  16276. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16277. };
  16278. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16279. if (!internalTexture) {
  16280. return -1;
  16281. }
  16282. internalTexture._initialSlot = channel;
  16283. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16284. if (channel !== internalTexture._designatedSlot) {
  16285. this._textureCollisions.addCount(1, false);
  16286. }
  16287. }
  16288. else {
  16289. if (channel !== internalTexture._designatedSlot) {
  16290. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16291. return internalTexture._designatedSlot;
  16292. }
  16293. else {
  16294. // No slot for this texture, let's pick a new one (if we find a free slot)
  16295. if (this._nextFreeTextureSlots.length) {
  16296. return this._nextFreeTextureSlots[0];
  16297. }
  16298. // We need to recycle the oldest bound texture, sorry.
  16299. this._textureCollisions.addCount(1, false);
  16300. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16301. }
  16302. }
  16303. }
  16304. return channel;
  16305. };
  16306. Engine.prototype._linkTrackers = function (previous, next) {
  16307. previous.next = next;
  16308. next.previous = previous;
  16309. };
  16310. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16311. var currentSlot = internalTexture._designatedSlot;
  16312. if (currentSlot === -1) {
  16313. return -1;
  16314. }
  16315. internalTexture._designatedSlot = -1;
  16316. if (this.disableTextureBindingOptimization) {
  16317. return -1;
  16318. }
  16319. // Remove from bound list
  16320. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16321. // Free the slot
  16322. this._boundTexturesCache[currentSlot] = null;
  16323. this._nextFreeTextureSlots.push(currentSlot);
  16324. return currentSlot;
  16325. };
  16326. Engine.prototype._activateCurrentTexture = function () {
  16327. if (this._currentTextureChannel !== this._activeChannel) {
  16328. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16329. this._currentTextureChannel = this._activeChannel;
  16330. }
  16331. };
  16332. /** @hidden */
  16333. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16334. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16335. if (force === void 0) { force = false; }
  16336. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16337. this._activeChannel = texture._designatedSlot;
  16338. }
  16339. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16340. var isTextureForRendering = texture && texture._initialSlot > -1;
  16341. if (currentTextureBound !== texture || force) {
  16342. if (currentTextureBound) {
  16343. this._removeDesignatedSlot(currentTextureBound);
  16344. }
  16345. this._activateCurrentTexture();
  16346. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16347. this._boundTexturesCache[this._activeChannel] = texture;
  16348. if (texture) {
  16349. if (!this.disableTextureBindingOptimization) {
  16350. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16351. if (slotIndex > -1) {
  16352. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16353. }
  16354. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16355. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16356. }
  16357. texture._designatedSlot = this._activeChannel;
  16358. }
  16359. }
  16360. else if (forTextureDataUpdate) {
  16361. this._activateCurrentTexture();
  16362. }
  16363. if (isTextureForRendering && !forTextureDataUpdate) {
  16364. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16365. }
  16366. };
  16367. /** @hidden */
  16368. Engine.prototype._bindTexture = function (channel, texture) {
  16369. if (channel < 0) {
  16370. return;
  16371. }
  16372. if (texture) {
  16373. channel = this._getCorrectTextureChannel(channel, texture);
  16374. }
  16375. this._activeChannel = channel;
  16376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16377. };
  16378. /**
  16379. * Sets a texture to the webGL context from a postprocess
  16380. * @param channel defines the channel to use
  16381. * @param postProcess defines the source postprocess
  16382. */
  16383. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16384. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16385. };
  16386. /**
  16387. * Binds the output of the passed in post process to the texture channel specified
  16388. * @param channel The channel the texture should be bound to
  16389. * @param postProcess The post process which's output should be bound
  16390. */
  16391. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16392. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16393. };
  16394. /**
  16395. * Unbind all textures from the webGL context
  16396. */
  16397. Engine.prototype.unbindAllTextures = function () {
  16398. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16399. this._activeChannel = channel;
  16400. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16401. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16402. if (this.webGLVersion > 1) {
  16403. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16404. }
  16405. }
  16406. };
  16407. /**
  16408. * Sets a texture to the according uniform.
  16409. * @param channel The texture channel
  16410. * @param uniform The uniform to set
  16411. * @param texture The texture to apply
  16412. */
  16413. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16414. if (channel < 0) {
  16415. return;
  16416. }
  16417. if (uniform) {
  16418. this._boundUniforms[channel] = uniform;
  16419. }
  16420. this._setTexture(channel, texture);
  16421. };
  16422. /**
  16423. * Sets a depth stencil texture from a render target to the according uniform.
  16424. * @param channel The texture channel
  16425. * @param uniform The uniform to set
  16426. * @param texture The render target texture containing the depth stencil texture to apply
  16427. */
  16428. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16429. if (channel < 0) {
  16430. return;
  16431. }
  16432. if (uniform) {
  16433. this._boundUniforms[channel] = uniform;
  16434. }
  16435. if (!texture || !texture.depthStencilTexture) {
  16436. this._setTexture(channel, null);
  16437. }
  16438. else {
  16439. this._setTexture(channel, texture, false, true);
  16440. }
  16441. };
  16442. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16443. var uniform = this._boundUniforms[sourceSlot];
  16444. if (uniform._currentState === destination) {
  16445. return;
  16446. }
  16447. this._gl.uniform1i(uniform, destination);
  16448. uniform._currentState = destination;
  16449. };
  16450. Engine.prototype._getTextureWrapMode = function (mode) {
  16451. switch (mode) {
  16452. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16453. return this._gl.REPEAT;
  16454. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16455. return this._gl.CLAMP_TO_EDGE;
  16456. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16457. return this._gl.MIRRORED_REPEAT;
  16458. }
  16459. return this._gl.REPEAT;
  16460. };
  16461. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16462. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16463. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16464. // Not ready?
  16465. if (!texture) {
  16466. if (this._boundTexturesCache[channel] != null) {
  16467. this._activeChannel = channel;
  16468. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16469. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16470. if (this.webGLVersion > 1) {
  16471. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16472. }
  16473. }
  16474. return false;
  16475. }
  16476. // Video
  16477. if (texture.video) {
  16478. this._activeChannel = channel;
  16479. texture.update();
  16480. }
  16481. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16482. texture.delayLoad();
  16483. return false;
  16484. }
  16485. var internalTexture;
  16486. if (depthStencilTexture) {
  16487. internalTexture = texture.depthStencilTexture;
  16488. }
  16489. else if (texture.isReady()) {
  16490. internalTexture = texture.getInternalTexture();
  16491. }
  16492. else if (texture.isCube) {
  16493. internalTexture = this.emptyCubeTexture;
  16494. }
  16495. else if (texture.is3D) {
  16496. internalTexture = this.emptyTexture3D;
  16497. }
  16498. else {
  16499. internalTexture = this.emptyTexture;
  16500. }
  16501. if (!isPartOfTextureArray) {
  16502. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16503. }
  16504. var needToBind = true;
  16505. if (this._boundTexturesCache[channel] === internalTexture) {
  16506. this._moveBoundTextureOnTop(internalTexture);
  16507. if (!isPartOfTextureArray) {
  16508. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16509. }
  16510. needToBind = false;
  16511. }
  16512. this._activeChannel = channel;
  16513. if (internalTexture && internalTexture.is3D) {
  16514. if (needToBind) {
  16515. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16516. }
  16517. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16518. internalTexture._cachedWrapU = texture.wrapU;
  16519. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16520. }
  16521. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16522. internalTexture._cachedWrapV = texture.wrapV;
  16523. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16524. }
  16525. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16526. internalTexture._cachedWrapR = texture.wrapR;
  16527. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16528. }
  16529. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16530. }
  16531. else if (internalTexture && internalTexture.isCube) {
  16532. if (needToBind) {
  16533. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16534. }
  16535. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16536. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16537. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16538. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16539. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16540. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16541. }
  16542. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16543. }
  16544. else {
  16545. if (needToBind) {
  16546. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16547. }
  16548. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16549. internalTexture._cachedWrapU = texture.wrapU;
  16550. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16551. }
  16552. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16553. internalTexture._cachedWrapV = texture.wrapV;
  16554. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16555. }
  16556. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16557. }
  16558. return true;
  16559. };
  16560. /**
  16561. * Sets an array of texture to the webGL context
  16562. * @param channel defines the channel where the texture array must be set
  16563. * @param uniform defines the associated uniform location
  16564. * @param textures defines the array of textures to bind
  16565. */
  16566. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16567. if (channel < 0 || !uniform) {
  16568. return;
  16569. }
  16570. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16571. this._textureUnits = new Int32Array(textures.length);
  16572. }
  16573. for (var i = 0; i < textures.length; i++) {
  16574. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16575. }
  16576. this._gl.uniform1iv(uniform, this._textureUnits);
  16577. for (var index = 0; index < textures.length; index++) {
  16578. this._setTexture(this._textureUnits[index], textures[index], true);
  16579. }
  16580. };
  16581. /** @hidden */
  16582. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16583. var internalTexture = texture.getInternalTexture();
  16584. if (!internalTexture) {
  16585. return;
  16586. }
  16587. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16588. var value = texture.anisotropicFilteringLevel;
  16589. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16590. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16591. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16592. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16593. }
  16594. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16595. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16596. internalTexture._cachedAnisotropicFilteringLevel = value;
  16597. }
  16598. };
  16599. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16600. this._bindTextureDirectly(target, texture, true, true);
  16601. this._gl.texParameterf(target, parameter, value);
  16602. };
  16603. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16604. if (texture) {
  16605. this._bindTextureDirectly(target, texture, true, true);
  16606. }
  16607. this._gl.texParameteri(target, parameter, value);
  16608. };
  16609. /**
  16610. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16611. * @param x defines the x coordinate of the rectangle where pixels must be read
  16612. * @param y defines the y coordinate of the rectangle where pixels must be read
  16613. * @param width defines the width of the rectangle where pixels must be read
  16614. * @param height defines the height of the rectangle where pixels must be read
  16615. * @returns a Uint8Array containing RGBA colors
  16616. */
  16617. Engine.prototype.readPixels = function (x, y, width, height) {
  16618. var data = new Uint8Array(height * width * 4);
  16619. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16620. return data;
  16621. };
  16622. /**
  16623. * Add an externaly attached data from its key.
  16624. * This method call will fail and return false, if such key already exists.
  16625. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16626. * @param key the unique key that identifies the data
  16627. * @param data the data object to associate to the key for this Engine instance
  16628. * @return true if no such key were already present and the data was added successfully, false otherwise
  16629. */
  16630. Engine.prototype.addExternalData = function (key, data) {
  16631. if (!this._externalData) {
  16632. this._externalData = new BABYLON.StringDictionary();
  16633. }
  16634. return this._externalData.add(key, data);
  16635. };
  16636. /**
  16637. * Get an externaly attached data from its key
  16638. * @param key the unique key that identifies the data
  16639. * @return the associated data, if present (can be null), or undefined if not present
  16640. */
  16641. Engine.prototype.getExternalData = function (key) {
  16642. if (!this._externalData) {
  16643. this._externalData = new BABYLON.StringDictionary();
  16644. }
  16645. return this._externalData.get(key);
  16646. };
  16647. /**
  16648. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16649. * @param key the unique key that identifies the data
  16650. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16651. * @return the associated data, can be null if the factory returned null.
  16652. */
  16653. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16654. if (!this._externalData) {
  16655. this._externalData = new BABYLON.StringDictionary();
  16656. }
  16657. return this._externalData.getOrAddWithFactory(key, factory);
  16658. };
  16659. /**
  16660. * Remove an externaly attached data from the Engine instance
  16661. * @param key the unique key that identifies the data
  16662. * @return true if the data was successfully removed, false if it doesn't exist
  16663. */
  16664. Engine.prototype.removeExternalData = function (key) {
  16665. if (!this._externalData) {
  16666. this._externalData = new BABYLON.StringDictionary();
  16667. }
  16668. return this._externalData.remove(key);
  16669. };
  16670. /**
  16671. * Unbind all vertex attributes from the webGL context
  16672. */
  16673. Engine.prototype.unbindAllAttributes = function () {
  16674. if (this._mustWipeVertexAttributes) {
  16675. this._mustWipeVertexAttributes = false;
  16676. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16677. this._gl.disableVertexAttribArray(i);
  16678. this._vertexAttribArraysEnabled[i] = false;
  16679. this._currentBufferPointers[i].active = false;
  16680. }
  16681. return;
  16682. }
  16683. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16684. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16685. continue;
  16686. }
  16687. this._gl.disableVertexAttribArray(i);
  16688. this._vertexAttribArraysEnabled[i] = false;
  16689. this._currentBufferPointers[i].active = false;
  16690. }
  16691. };
  16692. /**
  16693. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16694. */
  16695. Engine.prototype.releaseEffects = function () {
  16696. for (var name in this._compiledEffects) {
  16697. this._deleteProgram(this._compiledEffects[name]._program);
  16698. }
  16699. this._compiledEffects = {};
  16700. };
  16701. /**
  16702. * Dispose and release all associated resources
  16703. */
  16704. Engine.prototype.dispose = function () {
  16705. this.hideLoadingUI();
  16706. this.stopRenderLoop();
  16707. // Release postProcesses
  16708. while (this.postProcesses.length) {
  16709. this.postProcesses[0].dispose();
  16710. }
  16711. // Empty texture
  16712. if (this._emptyTexture) {
  16713. this._releaseTexture(this._emptyTexture);
  16714. this._emptyTexture = null;
  16715. }
  16716. if (this._emptyCubeTexture) {
  16717. this._releaseTexture(this._emptyCubeTexture);
  16718. this._emptyCubeTexture = null;
  16719. }
  16720. // Rescale PP
  16721. if (this._rescalePostProcess) {
  16722. this._rescalePostProcess.dispose();
  16723. }
  16724. // Release scenes
  16725. while (this.scenes.length) {
  16726. this.scenes[0].dispose();
  16727. }
  16728. // Release audio engine
  16729. if (Engine.audioEngine) {
  16730. Engine.audioEngine.dispose();
  16731. }
  16732. // Release effects
  16733. this.releaseEffects();
  16734. // Unbind
  16735. this.unbindAllAttributes();
  16736. this._boundUniforms = [];
  16737. if (this._dummyFramebuffer) {
  16738. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16739. }
  16740. //WebVR
  16741. this.disableVR();
  16742. // Events
  16743. if (BABYLON.Tools.IsWindowObjectExist()) {
  16744. window.removeEventListener("blur", this._onBlur);
  16745. window.removeEventListener("focus", this._onFocus);
  16746. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16747. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16748. if (this._renderingCanvas) {
  16749. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16750. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16751. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16752. if (!this._doNotHandleContextLost) {
  16753. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16754. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16755. }
  16756. }
  16757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16761. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16762. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16763. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16764. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16765. if (this._onVrDisplayConnect) {
  16766. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16767. if (this._onVrDisplayDisconnect) {
  16768. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16769. }
  16770. if (this._onVrDisplayPresentChange) {
  16771. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16772. }
  16773. this._onVrDisplayConnect = null;
  16774. this._onVrDisplayDisconnect = null;
  16775. }
  16776. }
  16777. // Remove from Instances
  16778. var index = Engine.Instances.indexOf(this);
  16779. if (index >= 0) {
  16780. Engine.Instances.splice(index, 1);
  16781. }
  16782. this._workingCanvas = null;
  16783. this._workingContext = null;
  16784. this._currentBufferPointers = [];
  16785. this._renderingCanvas = null;
  16786. this._currentProgram = null;
  16787. this._bindedRenderFunction = null;
  16788. this.onResizeObservable.clear();
  16789. this.onCanvasBlurObservable.clear();
  16790. this.onCanvasFocusObservable.clear();
  16791. this.onCanvasPointerOutObservable.clear();
  16792. this.onBeginFrameObservable.clear();
  16793. this.onEndFrameObservable.clear();
  16794. BABYLON.Effect.ResetCache();
  16795. // Abort active requests
  16796. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16797. var request = _a[_i];
  16798. request.abort();
  16799. }
  16800. };
  16801. // Loading screen
  16802. /**
  16803. * Display the loading screen
  16804. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16805. */
  16806. Engine.prototype.displayLoadingUI = function () {
  16807. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16808. return;
  16809. }
  16810. var loadingScreen = this.loadingScreen;
  16811. if (loadingScreen) {
  16812. loadingScreen.displayLoadingUI();
  16813. }
  16814. };
  16815. /**
  16816. * Hide the loading screen
  16817. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16818. */
  16819. Engine.prototype.hideLoadingUI = function () {
  16820. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16821. return;
  16822. }
  16823. var loadingScreen = this.loadingScreen;
  16824. if (loadingScreen) {
  16825. loadingScreen.hideLoadingUI();
  16826. }
  16827. };
  16828. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16829. /**
  16830. * Gets the current loading screen object
  16831. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16832. */
  16833. get: function () {
  16834. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16835. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16836. return this._loadingScreen;
  16837. },
  16838. /**
  16839. * Sets the current loading screen object
  16840. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16841. */
  16842. set: function (loadingScreen) {
  16843. this._loadingScreen = loadingScreen;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16849. /**
  16850. * Sets the current loading screen text
  16851. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16852. */
  16853. set: function (text) {
  16854. this.loadingScreen.loadingUIText = text;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16860. /**
  16861. * Sets the current loading screen background color
  16862. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16863. */
  16864. set: function (color) {
  16865. this.loadingScreen.loadingUIBackgroundColor = color;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. /**
  16871. * Attach a new callback raised when context lost event is fired
  16872. * @param callback defines the callback to call
  16873. */
  16874. Engine.prototype.attachContextLostEvent = function (callback) {
  16875. if (this._renderingCanvas) {
  16876. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16877. }
  16878. };
  16879. /**
  16880. * Attach a new callback raised when context restored event is fired
  16881. * @param callback defines the callback to call
  16882. */
  16883. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16884. if (this._renderingCanvas) {
  16885. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16886. }
  16887. };
  16888. /**
  16889. * Gets the source code of the vertex shader associated with a specific webGL program
  16890. * @param program defines the program to use
  16891. * @returns a string containing the source code of the vertex shader associated with the program
  16892. */
  16893. Engine.prototype.getVertexShaderSource = function (program) {
  16894. var shaders = this._gl.getAttachedShaders(program);
  16895. if (!shaders) {
  16896. return null;
  16897. }
  16898. return this._gl.getShaderSource(shaders[0]);
  16899. };
  16900. /**
  16901. * Gets the source code of the fragment shader associated with a specific webGL program
  16902. * @param program defines the program to use
  16903. * @returns a string containing the source code of the fragment shader associated with the program
  16904. */
  16905. Engine.prototype.getFragmentShaderSource = function (program) {
  16906. var shaders = this._gl.getAttachedShaders(program);
  16907. if (!shaders) {
  16908. return null;
  16909. }
  16910. return this._gl.getShaderSource(shaders[1]);
  16911. };
  16912. /**
  16913. * Get the current error code of the webGL context
  16914. * @returns the error code
  16915. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16916. */
  16917. Engine.prototype.getError = function () {
  16918. return this._gl.getError();
  16919. };
  16920. // FPS
  16921. /**
  16922. * Gets the current framerate
  16923. * @returns a number representing the framerate
  16924. */
  16925. Engine.prototype.getFps = function () {
  16926. return this._fps;
  16927. };
  16928. /**
  16929. * Gets the time spent between current and previous frame
  16930. * @returns a number representing the delta time in ms
  16931. */
  16932. Engine.prototype.getDeltaTime = function () {
  16933. return this._deltaTime;
  16934. };
  16935. Engine.prototype._measureFps = function () {
  16936. this._performanceMonitor.sampleFrame();
  16937. this._fps = this._performanceMonitor.averageFPS;
  16938. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16939. };
  16940. /** @hidden */
  16941. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16942. if (faceIndex === void 0) { faceIndex = -1; }
  16943. if (level === void 0) { level = 0; }
  16944. var gl = this._gl;
  16945. if (!this._dummyFramebuffer) {
  16946. var dummy = gl.createFramebuffer();
  16947. if (!dummy) {
  16948. throw new Error("Unable to create dummy framebuffer");
  16949. }
  16950. this._dummyFramebuffer = dummy;
  16951. }
  16952. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16953. if (faceIndex > -1) {
  16954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16955. }
  16956. else {
  16957. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16958. }
  16959. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16960. var buffer;
  16961. switch (readType) {
  16962. case gl.UNSIGNED_BYTE:
  16963. buffer = new Uint8Array(4 * width * height);
  16964. readType = gl.UNSIGNED_BYTE;
  16965. break;
  16966. default:
  16967. buffer = new Float32Array(4 * width * height);
  16968. readType = gl.FLOAT;
  16969. break;
  16970. }
  16971. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16972. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16973. return buffer;
  16974. };
  16975. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16976. if (this._webGLVersion > 1) {
  16977. return this._caps.colorBufferFloat;
  16978. }
  16979. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16980. };
  16981. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16982. if (this._webGLVersion > 1) {
  16983. return this._caps.colorBufferFloat;
  16984. }
  16985. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16986. };
  16987. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16988. Engine.prototype._canRenderToFramebuffer = function (type) {
  16989. var gl = this._gl;
  16990. //clear existing errors
  16991. while (gl.getError() !== gl.NO_ERROR) { }
  16992. var successful = true;
  16993. var texture = gl.createTexture();
  16994. gl.bindTexture(gl.TEXTURE_2D, texture);
  16995. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16998. var fb = gl.createFramebuffer();
  16999. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17001. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17002. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17003. successful = successful && (gl.getError() === gl.NO_ERROR);
  17004. //try render by clearing frame buffer's color buffer
  17005. if (successful) {
  17006. gl.clear(gl.COLOR_BUFFER_BIT);
  17007. successful = successful && (gl.getError() === gl.NO_ERROR);
  17008. }
  17009. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17010. if (successful) {
  17011. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17012. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17013. var readFormat = gl.RGBA;
  17014. var readType = gl.UNSIGNED_BYTE;
  17015. var buffer = new Uint8Array(4);
  17016. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17017. successful = successful && (gl.getError() === gl.NO_ERROR);
  17018. }
  17019. //clean up
  17020. gl.deleteTexture(texture);
  17021. gl.deleteFramebuffer(fb);
  17022. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17023. //clear accumulated errors
  17024. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17025. return successful;
  17026. };
  17027. /** @hidden */
  17028. Engine.prototype._getWebGLTextureType = function (type) {
  17029. if (type === Engine.TEXTURETYPE_FLOAT) {
  17030. return this._gl.FLOAT;
  17031. }
  17032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17033. // Add Half Float Constant.
  17034. return this._gl.HALF_FLOAT_OES;
  17035. }
  17036. return this._gl.UNSIGNED_BYTE;
  17037. };
  17038. ;
  17039. Engine.prototype._getInternalFormat = function (format) {
  17040. var internalFormat = this._gl.RGBA;
  17041. switch (format) {
  17042. case Engine.TEXTUREFORMAT_ALPHA:
  17043. internalFormat = this._gl.ALPHA;
  17044. break;
  17045. case Engine.TEXTUREFORMAT_LUMINANCE:
  17046. internalFormat = this._gl.LUMINANCE;
  17047. break;
  17048. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17049. internalFormat = this._gl.LUMINANCE_ALPHA;
  17050. break;
  17051. case Engine.TEXTUREFORMAT_RGB:
  17052. internalFormat = this._gl.RGB;
  17053. break;
  17054. case Engine.TEXTUREFORMAT_RGBA:
  17055. internalFormat = this._gl.RGBA;
  17056. break;
  17057. case Engine.TEXTUREFORMAT_R:
  17058. internalFormat = this._gl.RED;
  17059. break;
  17060. case Engine.TEXTUREFORMAT_RG:
  17061. internalFormat = this._gl.RG;
  17062. break;
  17063. }
  17064. return internalFormat;
  17065. };
  17066. /** @hidden */
  17067. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17068. if (this._webGLVersion === 1) {
  17069. if (format !== undefined) {
  17070. switch (format) {
  17071. case Engine.TEXTUREFORMAT_LUMINANCE:
  17072. return this._gl.LUMINANCE;
  17073. case Engine.TEXTUREFORMAT_ALPHA:
  17074. return this._gl.ALPHA;
  17075. }
  17076. }
  17077. return this._gl.RGBA;
  17078. }
  17079. if (type === Engine.TEXTURETYPE_FLOAT) {
  17080. if (format !== undefined) {
  17081. switch (format) {
  17082. case Engine.TEXTUREFORMAT_R:
  17083. return this._gl.R32F;
  17084. case Engine.TEXTUREFORMAT_RG:
  17085. return this._gl.RG32F;
  17086. case Engine.TEXTUREFORMAT_RGB:
  17087. return this._gl.RGB32F;
  17088. }
  17089. }
  17090. return this._gl.RGBA32F;
  17091. }
  17092. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17093. if (format) {
  17094. switch (format) {
  17095. case Engine.TEXTUREFORMAT_R:
  17096. return this._gl.R16F;
  17097. case Engine.TEXTUREFORMAT_RG:
  17098. return this._gl.RG16F;
  17099. case Engine.TEXTUREFORMAT_RGB:
  17100. return this._gl.RGB16F;
  17101. }
  17102. }
  17103. return this._gl.RGBA16F;
  17104. }
  17105. if (format !== undefined) {
  17106. switch (format) {
  17107. case Engine.TEXTUREFORMAT_LUMINANCE:
  17108. return this._gl.LUMINANCE;
  17109. case Engine.TEXTUREFORMAT_RGB:
  17110. return this._gl.RGB;
  17111. case Engine.TEXTUREFORMAT_R:
  17112. return this._gl.R8;
  17113. case Engine.TEXTUREFORMAT_RG:
  17114. return this._gl.RG8;
  17115. case Engine.TEXTUREFORMAT_ALPHA:
  17116. return this._gl.ALPHA;
  17117. }
  17118. }
  17119. return this._gl.RGBA;
  17120. };
  17121. ;
  17122. /** @hidden */
  17123. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17124. if (type === Engine.TEXTURETYPE_FLOAT) {
  17125. return this._gl.RGBA32F;
  17126. }
  17127. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17128. return this._gl.RGBA16F;
  17129. }
  17130. return this._gl.RGBA8;
  17131. };
  17132. ;
  17133. /**
  17134. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17135. * @return the new query
  17136. */
  17137. Engine.prototype.createQuery = function () {
  17138. return this._gl.createQuery();
  17139. };
  17140. /**
  17141. * Delete and release a webGL query
  17142. * @param query defines the query to delete
  17143. * @return the current engine
  17144. */
  17145. Engine.prototype.deleteQuery = function (query) {
  17146. this._gl.deleteQuery(query);
  17147. return this;
  17148. };
  17149. /**
  17150. * Check if a given query has resolved and got its value
  17151. * @param query defines the query to check
  17152. * @returns true if the query got its value
  17153. */
  17154. Engine.prototype.isQueryResultAvailable = function (query) {
  17155. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17156. };
  17157. /**
  17158. * Gets the value of a given query
  17159. * @param query defines the query to check
  17160. * @returns the value of the query
  17161. */
  17162. Engine.prototype.getQueryResult = function (query) {
  17163. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17164. };
  17165. /**
  17166. * Initiates an occlusion query
  17167. * @param algorithmType defines the algorithm to use
  17168. * @param query defines the query to use
  17169. * @returns the current engine
  17170. * @see http://doc.babylonjs.com/features/occlusionquery
  17171. */
  17172. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17173. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17174. this._gl.beginQuery(glAlgorithm, query);
  17175. return this;
  17176. };
  17177. /**
  17178. * Ends an occlusion query
  17179. * @see http://doc.babylonjs.com/features/occlusionquery
  17180. * @param algorithmType defines the algorithm to use
  17181. * @returns the current engine
  17182. */
  17183. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17184. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17185. this._gl.endQuery(glAlgorithm);
  17186. return this;
  17187. };
  17188. /* Time queries */
  17189. Engine.prototype._createTimeQuery = function () {
  17190. var timerQuery = this._caps.timerQuery;
  17191. if (timerQuery.createQueryEXT) {
  17192. return timerQuery.createQueryEXT();
  17193. }
  17194. return this.createQuery();
  17195. };
  17196. Engine.prototype._deleteTimeQuery = function (query) {
  17197. var timerQuery = this._caps.timerQuery;
  17198. if (timerQuery.deleteQueryEXT) {
  17199. timerQuery.deleteQueryEXT(query);
  17200. return;
  17201. }
  17202. this.deleteQuery(query);
  17203. };
  17204. Engine.prototype._getTimeQueryResult = function (query) {
  17205. var timerQuery = this._caps.timerQuery;
  17206. if (timerQuery.getQueryObjectEXT) {
  17207. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17208. }
  17209. return this.getQueryResult(query);
  17210. };
  17211. Engine.prototype._getTimeQueryAvailability = function (query) {
  17212. var timerQuery = this._caps.timerQuery;
  17213. if (timerQuery.getQueryObjectEXT) {
  17214. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17215. }
  17216. return this.isQueryResultAvailable(query);
  17217. };
  17218. /**
  17219. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17220. * Please note that only one query can be issued at a time
  17221. * @returns a time token used to track the time span
  17222. */
  17223. Engine.prototype.startTimeQuery = function () {
  17224. var timerQuery = this._caps.timerQuery;
  17225. if (!timerQuery) {
  17226. return null;
  17227. }
  17228. var token = new BABYLON._TimeToken();
  17229. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17230. if (this._caps.canUseTimestampForTimerQuery) {
  17231. token._startTimeQuery = this._createTimeQuery();
  17232. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17233. }
  17234. else {
  17235. if (this._currentNonTimestampToken) {
  17236. return this._currentNonTimestampToken;
  17237. }
  17238. token._timeElapsedQuery = this._createTimeQuery();
  17239. if (timerQuery.beginQueryEXT) {
  17240. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17241. }
  17242. else {
  17243. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17244. }
  17245. this._currentNonTimestampToken = token;
  17246. }
  17247. return token;
  17248. };
  17249. /**
  17250. * Ends a time query
  17251. * @param token defines the token used to measure the time span
  17252. * @returns the time spent (in ns)
  17253. */
  17254. Engine.prototype.endTimeQuery = function (token) {
  17255. var timerQuery = this._caps.timerQuery;
  17256. if (!timerQuery || !token) {
  17257. return -1;
  17258. }
  17259. if (this._caps.canUseTimestampForTimerQuery) {
  17260. if (!token._startTimeQuery) {
  17261. return -1;
  17262. }
  17263. if (!token._endTimeQuery) {
  17264. token._endTimeQuery = this._createTimeQuery();
  17265. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17266. }
  17267. }
  17268. else if (!token._timeElapsedQueryEnded) {
  17269. if (!token._timeElapsedQuery) {
  17270. return -1;
  17271. }
  17272. if (timerQuery.endQueryEXT) {
  17273. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17274. }
  17275. else {
  17276. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17277. }
  17278. token._timeElapsedQueryEnded = true;
  17279. }
  17280. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17281. var available = false;
  17282. if (token._endTimeQuery) {
  17283. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17284. }
  17285. else if (token._timeElapsedQuery) {
  17286. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17287. }
  17288. if (available && !disjoint) {
  17289. var result = 0;
  17290. if (this._caps.canUseTimestampForTimerQuery) {
  17291. if (!token._startTimeQuery || !token._endTimeQuery) {
  17292. return -1;
  17293. }
  17294. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17295. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17296. result = timeEnd - timeStart;
  17297. this._deleteTimeQuery(token._startTimeQuery);
  17298. this._deleteTimeQuery(token._endTimeQuery);
  17299. token._startTimeQuery = null;
  17300. token._endTimeQuery = null;
  17301. }
  17302. else {
  17303. if (!token._timeElapsedQuery) {
  17304. return -1;
  17305. }
  17306. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17307. this._deleteTimeQuery(token._timeElapsedQuery);
  17308. token._timeElapsedQuery = null;
  17309. token._timeElapsedQueryEnded = false;
  17310. this._currentNonTimestampToken = null;
  17311. }
  17312. return result;
  17313. }
  17314. return -1;
  17315. };
  17316. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17317. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17318. };
  17319. // Transform feedback
  17320. /**
  17321. * Creates a webGL transform feedback object
  17322. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17323. * @returns the webGL transform feedback object
  17324. */
  17325. Engine.prototype.createTransformFeedback = function () {
  17326. return this._gl.createTransformFeedback();
  17327. };
  17328. /**
  17329. * Delete a webGL transform feedback object
  17330. * @param value defines the webGL transform feedback object to delete
  17331. */
  17332. Engine.prototype.deleteTransformFeedback = function (value) {
  17333. this._gl.deleteTransformFeedback(value);
  17334. };
  17335. /**
  17336. * Bind a webGL transform feedback object to the webgl context
  17337. * @param value defines the webGL transform feedback object to bind
  17338. */
  17339. Engine.prototype.bindTransformFeedback = function (value) {
  17340. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17341. };
  17342. /**
  17343. * Begins a transform feedback operation
  17344. * @param usePoints defines if points or triangles must be used
  17345. */
  17346. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17347. if (usePoints === void 0) { usePoints = true; }
  17348. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17349. };
  17350. /**
  17351. * Ends a transform feedback operation
  17352. */
  17353. Engine.prototype.endTransformFeedback = function () {
  17354. this._gl.endTransformFeedback();
  17355. };
  17356. /**
  17357. * Specify the varyings to use with transform feedback
  17358. * @param program defines the associated webGL program
  17359. * @param value defines the list of strings representing the varying names
  17360. */
  17361. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17362. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17363. };
  17364. /**
  17365. * Bind a webGL buffer for a transform feedback operation
  17366. * @param value defines the webGL buffer to bind
  17367. */
  17368. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17369. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17370. };
  17371. /** @hidden */
  17372. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17373. var _this = this;
  17374. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17375. this._activeRequests.push(request);
  17376. request.onCompleteObservable.add(function (request) {
  17377. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17378. });
  17379. return request;
  17380. };
  17381. /** @hidden */
  17382. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17383. var _this = this;
  17384. return new Promise(function (resolve, reject) {
  17385. _this._loadFile(url, function (data) {
  17386. resolve(data);
  17387. }, undefined, database, useArrayBuffer, function (request, exception) {
  17388. reject(exception);
  17389. });
  17390. });
  17391. };
  17392. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17393. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17394. var onload = function (data) {
  17395. loadedFiles[index] = data;
  17396. loadedFiles._internalCount++;
  17397. if (loadedFiles._internalCount === 6) {
  17398. onfinish(loadedFiles);
  17399. }
  17400. };
  17401. var onerror = function (request, exception) {
  17402. if (onErrorCallBack && request) {
  17403. onErrorCallBack(request.status + " " + request.statusText, exception);
  17404. }
  17405. };
  17406. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17407. };
  17408. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17409. if (onError === void 0) { onError = null; }
  17410. var loadedFiles = [];
  17411. loadedFiles._internalCount = 0;
  17412. for (var index = 0; index < 6; index++) {
  17413. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17414. }
  17415. };
  17416. // Statics
  17417. /**
  17418. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17419. * @returns true if the engine can be created
  17420. * @ignorenaming
  17421. */
  17422. Engine.isSupported = function () {
  17423. try {
  17424. var tempcanvas = document.createElement("canvas");
  17425. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17426. return gl != null && !!window.WebGLRenderingContext;
  17427. }
  17428. catch (e) {
  17429. return false;
  17430. }
  17431. };
  17432. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17433. Engine.ExceptionList = [
  17434. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17435. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17436. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17437. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17438. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17439. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17440. ];
  17441. /** Gets the list of created engines */
  17442. Engine.Instances = new Array();
  17443. // Const statics
  17444. Engine._ALPHA_DISABLE = 0;
  17445. Engine._ALPHA_ADD = 1;
  17446. Engine._ALPHA_COMBINE = 2;
  17447. Engine._ALPHA_SUBTRACT = 3;
  17448. Engine._ALPHA_MULTIPLY = 4;
  17449. Engine._ALPHA_MAXIMIZED = 5;
  17450. Engine._ALPHA_ONEONE = 6;
  17451. Engine._ALPHA_PREMULTIPLIED = 7;
  17452. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17453. Engine._ALPHA_INTERPOLATE = 9;
  17454. Engine._ALPHA_SCREENMODE = 10;
  17455. Engine._DELAYLOADSTATE_NONE = 0;
  17456. Engine._DELAYLOADSTATE_LOADED = 1;
  17457. Engine._DELAYLOADSTATE_LOADING = 2;
  17458. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17459. Engine._TEXTUREFORMAT_ALPHA = 0;
  17460. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17461. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17462. Engine._TEXTUREFORMAT_RGB = 4;
  17463. Engine._TEXTUREFORMAT_RGBA = 5;
  17464. Engine._TEXTUREFORMAT_R = 6;
  17465. Engine._TEXTUREFORMAT_RG = 7;
  17466. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17467. Engine._TEXTURETYPE_FLOAT = 1;
  17468. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17469. // Depht or Stencil test Constants.
  17470. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17471. 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.
  17472. 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.
  17473. 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.
  17474. 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.
  17475. 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.
  17476. 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.
  17477. 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.
  17478. // Stencil Actions Constants.
  17479. Engine._KEEP = 0x1E00;
  17480. Engine._REPLACE = 0x1E01;
  17481. Engine._INCR = 0x1E02;
  17482. Engine._DECR = 0x1E03;
  17483. Engine._INVERT = 0x150A;
  17484. Engine._INCR_WRAP = 0x8507;
  17485. Engine._DECR_WRAP = 0x8508;
  17486. // Texture rescaling mode
  17487. Engine._SCALEMODE_FLOOR = 1;
  17488. Engine._SCALEMODE_NEAREST = 2;
  17489. Engine._SCALEMODE_CEILING = 3;
  17490. // Updatable statics so stick with vars here
  17491. /**
  17492. * Gets or sets the epsilon value used by collision engine
  17493. */
  17494. Engine.CollisionsEpsilon = 0.001;
  17495. /**
  17496. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17497. */
  17498. Engine.CodeRepository = "src/";
  17499. /**
  17500. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17501. */
  17502. Engine.ShadersRepository = "src/Shaders/";
  17503. return Engine;
  17504. }());
  17505. BABYLON.Engine = Engine;
  17506. })(BABYLON || (BABYLON = {}));
  17507. //# sourceMappingURL=babylon.engine.js.map
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. /**
  17511. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17512. */
  17513. var Node = /** @class */ (function () {
  17514. /**
  17515. * Creates a new Node
  17516. * @param {string} name - the name and id to be given to this node
  17517. * @param {BABYLON.Scene} the scene this node will be added to
  17518. */
  17519. function Node(name, scene) {
  17520. if (scene === void 0) { scene = null; }
  17521. /**
  17522. * Gets or sets a string used to store user defined state for the node
  17523. */
  17524. this.state = "";
  17525. /**
  17526. * Gets or sets an object used to store user defined information for the node
  17527. */
  17528. this.metadata = null;
  17529. /**
  17530. * Gets or sets a boolean used to define if the node must be serialized
  17531. */
  17532. this.doNotSerialize = false;
  17533. /** @hidden */
  17534. this._isDisposed = false;
  17535. /**
  17536. * Gets a list of Animations associated with the node
  17537. */
  17538. this.animations = new Array();
  17539. this._ranges = {};
  17540. this._isEnabled = true;
  17541. this._isReady = true;
  17542. /** @hidden */
  17543. this._currentRenderId = -1;
  17544. this._parentRenderId = -1;
  17545. this._childRenderId = -1;
  17546. this._animationPropertiesOverride = null;
  17547. /**
  17548. * An event triggered when the mesh is disposed
  17549. */
  17550. this.onDisposeObservable = new BABYLON.Observable();
  17551. // Behaviors
  17552. this._behaviors = new Array();
  17553. this.name = name;
  17554. this.id = name;
  17555. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17556. this.uniqueId = this._scene.getUniqueId();
  17557. this._initCache();
  17558. }
  17559. /**
  17560. * Gets a boolean indicating if the node has been disposed
  17561. * @returns true if the node was disposed
  17562. */
  17563. Node.prototype.isDisposed = function () {
  17564. return this._isDisposed;
  17565. };
  17566. Object.defineProperty(Node.prototype, "parent", {
  17567. get: function () {
  17568. return this._parentNode;
  17569. },
  17570. /**
  17571. * Gets or sets the parent of the node
  17572. */
  17573. set: function (parent) {
  17574. if (this._parentNode === parent) {
  17575. return;
  17576. }
  17577. // Remove self from list of children of parent
  17578. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17579. var index = this._parentNode._children.indexOf(this);
  17580. if (index !== -1) {
  17581. this._parentNode._children.splice(index, 1);
  17582. }
  17583. }
  17584. // Store new parent
  17585. this._parentNode = parent;
  17586. // Add as child to new parent
  17587. if (this._parentNode) {
  17588. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17589. this._parentNode._children = new Array();
  17590. }
  17591. this._parentNode._children.push(this);
  17592. }
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17598. /**
  17599. * Gets or sets the animation properties override
  17600. */
  17601. get: function () {
  17602. if (!this._animationPropertiesOverride) {
  17603. return this._scene.animationPropertiesOverride;
  17604. }
  17605. return this._animationPropertiesOverride;
  17606. },
  17607. set: function (value) {
  17608. this._animationPropertiesOverride = value;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Gets a string idenfifying the name of the class
  17615. * @returns "Node" string
  17616. */
  17617. Node.prototype.getClassName = function () {
  17618. return "Node";
  17619. };
  17620. Object.defineProperty(Node.prototype, "onDispose", {
  17621. /**
  17622. * Sets a callback that will be raised when the node will be disposed
  17623. */
  17624. set: function (callback) {
  17625. if (this._onDisposeObserver) {
  17626. this.onDisposeObservable.remove(this._onDisposeObserver);
  17627. }
  17628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets the scene of the node
  17635. * @returns a {BABYLON.Scene}
  17636. */
  17637. Node.prototype.getScene = function () {
  17638. return this._scene;
  17639. };
  17640. /**
  17641. * Gets the engine of the node
  17642. * @returns a {BABYLON.Engine}
  17643. */
  17644. Node.prototype.getEngine = function () {
  17645. return this._scene.getEngine();
  17646. };
  17647. /**
  17648. * Attach a behavior to the node
  17649. * @see http://doc.babylonjs.com/features/behaviour
  17650. * @param behavior defines the behavior to attach
  17651. * @returns the current Node
  17652. */
  17653. Node.prototype.addBehavior = function (behavior) {
  17654. var _this = this;
  17655. var index = this._behaviors.indexOf(behavior);
  17656. if (index !== -1) {
  17657. return this;
  17658. }
  17659. behavior.init();
  17660. if (this._scene.isLoading) {
  17661. // We defer the attach when the scene will be loaded
  17662. this._scene.onDataLoadedObservable.addOnce(function () {
  17663. behavior.attach(_this);
  17664. });
  17665. }
  17666. else {
  17667. behavior.attach(this);
  17668. }
  17669. this._behaviors.push(behavior);
  17670. return this;
  17671. };
  17672. /**
  17673. * Remove an attached behavior
  17674. * @see http://doc.babylonjs.com/features/behaviour
  17675. * @param behavior defines the behavior to attach
  17676. * @returns the current Node
  17677. */
  17678. Node.prototype.removeBehavior = function (behavior) {
  17679. var index = this._behaviors.indexOf(behavior);
  17680. if (index === -1) {
  17681. return this;
  17682. }
  17683. this._behaviors[index].detach();
  17684. this._behaviors.splice(index, 1);
  17685. return this;
  17686. };
  17687. Object.defineProperty(Node.prototype, "behaviors", {
  17688. /**
  17689. * Gets the list of attached behaviors
  17690. * @see http://doc.babylonjs.com/features/behaviour
  17691. */
  17692. get: function () {
  17693. return this._behaviors;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. /**
  17699. * Gets an attached behavior by name
  17700. * @param name defines the name of the behavior to look for
  17701. * @see http://doc.babylonjs.com/features/behaviour
  17702. * @returns null if behavior was not found else the requested behavior
  17703. */
  17704. Node.prototype.getBehaviorByName = function (name) {
  17705. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17706. var behavior = _a[_i];
  17707. if (behavior.name === name) {
  17708. return behavior;
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. /**
  17714. * Returns the world matrix of the node
  17715. * @returns a matrix containing the node's world matrix
  17716. */
  17717. Node.prototype.getWorldMatrix = function () {
  17718. return BABYLON.Matrix.Identity();
  17719. };
  17720. /** @hidden */
  17721. Node.prototype._getWorldMatrixDeterminant = function () {
  17722. return 1;
  17723. };
  17724. // override it in derived class if you add new variables to the cache
  17725. // and call the parent class method
  17726. /** @hidden */
  17727. Node.prototype._initCache = function () {
  17728. this._cache = {};
  17729. this._cache.parent = undefined;
  17730. };
  17731. /** @hidden */
  17732. Node.prototype.updateCache = function (force) {
  17733. if (!force && this.isSynchronized())
  17734. return;
  17735. this._cache.parent = this.parent;
  17736. this._updateCache();
  17737. };
  17738. // override it in derived class if you add new variables to the cache
  17739. // and call the parent class method if !ignoreParentClass
  17740. /** @hidden */
  17741. Node.prototype._updateCache = function (ignoreParentClass) {
  17742. };
  17743. // override it in derived class if you add new variables to the cache
  17744. /** @hidden */
  17745. Node.prototype._isSynchronized = function () {
  17746. return true;
  17747. };
  17748. /** @hidden */
  17749. Node.prototype._markSyncedWithParent = function () {
  17750. if (this.parent) {
  17751. this._parentRenderId = this.parent._childRenderId;
  17752. }
  17753. };
  17754. /** @hidden */
  17755. Node.prototype.isSynchronizedWithParent = function () {
  17756. if (!this.parent) {
  17757. return true;
  17758. }
  17759. if (this._parentRenderId !== this.parent._childRenderId) {
  17760. return false;
  17761. }
  17762. return this.parent.isSynchronized();
  17763. };
  17764. /** @hidden */
  17765. Node.prototype.isSynchronized = function (updateCache) {
  17766. var check = this.hasNewParent();
  17767. check = check || !this.isSynchronizedWithParent();
  17768. check = check || !this._isSynchronized();
  17769. if (updateCache)
  17770. this.updateCache(true);
  17771. return !check;
  17772. };
  17773. /** @hidden */
  17774. Node.prototype.hasNewParent = function (update) {
  17775. if (this._cache.parent === this.parent)
  17776. return false;
  17777. if (update)
  17778. this._cache.parent = this.parent;
  17779. return true;
  17780. };
  17781. /**
  17782. * Is this node ready to be used/rendered
  17783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17784. * @return true if the node is ready
  17785. */
  17786. Node.prototype.isReady = function (completeCheck) {
  17787. if (completeCheck === void 0) { completeCheck = false; }
  17788. return this._isReady;
  17789. };
  17790. /**
  17791. * Is this node enabled?
  17792. * 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
  17793. * @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
  17794. * @return whether this node (and its parent) is enabled
  17795. */
  17796. Node.prototype.isEnabled = function (checkAncestors) {
  17797. if (checkAncestors === void 0) { checkAncestors = true; }
  17798. if (checkAncestors === false) {
  17799. return this._isEnabled;
  17800. }
  17801. if (this._isEnabled === false) {
  17802. return false;
  17803. }
  17804. if (this.parent !== undefined && this.parent !== null) {
  17805. return this.parent.isEnabled(checkAncestors);
  17806. }
  17807. return true;
  17808. };
  17809. /**
  17810. * Set the enabled state of this node
  17811. * @param value defines the new enabled state
  17812. */
  17813. Node.prototype.setEnabled = function (value) {
  17814. this._isEnabled = value;
  17815. };
  17816. /**
  17817. * Is this node a descendant of the given node?
  17818. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17819. * @param ancestor defines the parent node to inspect
  17820. * @returns a boolean indicating if this node is a descendant of the given node
  17821. */
  17822. Node.prototype.isDescendantOf = function (ancestor) {
  17823. if (this.parent) {
  17824. if (this.parent === ancestor) {
  17825. return true;
  17826. }
  17827. return this.parent.isDescendantOf(ancestor);
  17828. }
  17829. return false;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17833. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17834. if (!this._children) {
  17835. return;
  17836. }
  17837. for (var index = 0; index < this._children.length; index++) {
  17838. var item = this._children[index];
  17839. if (!predicate || predicate(item)) {
  17840. results.push(item);
  17841. }
  17842. if (!directDescendantsOnly) {
  17843. item._getDescendants(results, false, predicate);
  17844. }
  17845. }
  17846. };
  17847. /**
  17848. * Will return all nodes that have this node as ascendant
  17849. * @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
  17850. * @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
  17851. * @return all children nodes of all types
  17852. */
  17853. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17854. var results = new Array();
  17855. this._getDescendants(results, directDescendantsOnly, predicate);
  17856. return results;
  17857. };
  17858. /**
  17859. * Get all child-meshes of this node
  17860. * @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
  17861. * @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
  17862. * @returns an array of {BABYLON.AbstractMesh}
  17863. */
  17864. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17865. var results = [];
  17866. this._getDescendants(results, directDescendantsOnly, function (node) {
  17867. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17868. });
  17869. return results;
  17870. };
  17871. /**
  17872. * Get all child-transformNodes of this node
  17873. * @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
  17874. * @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
  17875. * @returns an array of {BABYLON.TransformNode}
  17876. */
  17877. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17878. var results = [];
  17879. this._getDescendants(results, directDescendantsOnly, function (node) {
  17880. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17881. });
  17882. return results;
  17883. };
  17884. /**
  17885. * Get all direct children of this node
  17886. * @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
  17887. * @returns an array of {BABYLON.Node}
  17888. */
  17889. Node.prototype.getChildren = function (predicate) {
  17890. return this.getDescendants(true, predicate);
  17891. };
  17892. /** @hidden */
  17893. Node.prototype._setReady = function (state) {
  17894. if (state === this._isReady) {
  17895. return;
  17896. }
  17897. if (!state) {
  17898. this._isReady = false;
  17899. return;
  17900. }
  17901. if (this.onReady) {
  17902. this.onReady(this);
  17903. }
  17904. this._isReady = true;
  17905. };
  17906. /**
  17907. * Get an animation by name
  17908. * @param name defines the name of the animation to look for
  17909. * @returns null if not found else the requested animation
  17910. */
  17911. Node.prototype.getAnimationByName = function (name) {
  17912. for (var i = 0; i < this.animations.length; i++) {
  17913. var animation = this.animations[i];
  17914. if (animation.name === name) {
  17915. return animation;
  17916. }
  17917. }
  17918. return null;
  17919. };
  17920. /**
  17921. * Creates an animation range for this node
  17922. * @param name defines the name of the range
  17923. * @param from defines the starting key
  17924. * @param to defines the end key
  17925. */
  17926. Node.prototype.createAnimationRange = function (name, from, to) {
  17927. // check name not already in use
  17928. if (!this._ranges[name]) {
  17929. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17930. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17931. if (this.animations[i]) {
  17932. this.animations[i].createRange(name, from, to);
  17933. }
  17934. }
  17935. }
  17936. };
  17937. /**
  17938. * Delete a specific animation range
  17939. * @param name defines the name of the range to delete
  17940. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17941. */
  17942. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17943. if (deleteFrames === void 0) { deleteFrames = true; }
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].deleteRange(name, deleteFrames);
  17947. }
  17948. }
  17949. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17950. };
  17951. /**
  17952. * Get an animation range by name
  17953. * @param name defines the name of the animation range to look for
  17954. * @returns null if not found else the requested animation range
  17955. */
  17956. Node.prototype.getAnimationRange = function (name) {
  17957. return this._ranges[name];
  17958. };
  17959. /**
  17960. * Will start the animation sequence
  17961. * @param name defines the range frames for animation sequence
  17962. * @param loop defines if the animation should loop (false by default)
  17963. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17964. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17965. * @returns the object created for this animation. If range does not exist, it will return null
  17966. */
  17967. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17968. var range = this.getAnimationRange(name);
  17969. if (!range) {
  17970. return null;
  17971. }
  17972. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17973. };
  17974. /**
  17975. * Serialize animation ranges into a JSON compatible object
  17976. * @returns serialization object
  17977. */
  17978. Node.prototype.serializeAnimationRanges = function () {
  17979. var serializationRanges = [];
  17980. for (var name in this._ranges) {
  17981. var localRange = this._ranges[name];
  17982. if (!localRange) {
  17983. continue;
  17984. }
  17985. var range = {};
  17986. range.name = name;
  17987. range.from = localRange.from;
  17988. range.to = localRange.to;
  17989. serializationRanges.push(range);
  17990. }
  17991. return serializationRanges;
  17992. };
  17993. /**
  17994. * Computes the world matrix of the node
  17995. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17996. * @returns the world matrix
  17997. */
  17998. Node.prototype.computeWorldMatrix = function (force) {
  17999. return BABYLON.Matrix.Identity();
  18000. };
  18001. /**
  18002. * Releases resources associated with this node.
  18003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18005. */
  18006. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18008. if (!doNotRecurse) {
  18009. var nodes = this.getDescendants(true);
  18010. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18011. var node = nodes_1[_i];
  18012. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18013. }
  18014. }
  18015. else {
  18016. var transformNodes = this.getChildTransformNodes(true);
  18017. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18018. var transformNode = transformNodes_1[_a];
  18019. transformNode.parent = null;
  18020. transformNode.computeWorldMatrix(true);
  18021. }
  18022. }
  18023. this.parent = null;
  18024. // Callback
  18025. this.onDisposeObservable.notifyObservers(this);
  18026. this.onDisposeObservable.clear();
  18027. // Behaviors
  18028. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18029. var behavior = _c[_b];
  18030. behavior.detach();
  18031. }
  18032. this._behaviors = [];
  18033. this._isDisposed = true;
  18034. };
  18035. /**
  18036. * Parse animation range data from a serialization object and store them into a given node
  18037. * @param node defines where to store the animation ranges
  18038. * @param parsedNode defines the serialization object to read data from
  18039. * @param scene defines the hosting scene
  18040. */
  18041. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18042. if (parsedNode.ranges) {
  18043. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18044. var data = parsedNode.ranges[index];
  18045. node.createAnimationRange(data.name, data.from, data.to);
  18046. }
  18047. }
  18048. };
  18049. __decorate([
  18050. BABYLON.serialize()
  18051. ], Node.prototype, "name", void 0);
  18052. __decorate([
  18053. BABYLON.serialize()
  18054. ], Node.prototype, "id", void 0);
  18055. __decorate([
  18056. BABYLON.serialize()
  18057. ], Node.prototype, "uniqueId", void 0);
  18058. __decorate([
  18059. BABYLON.serialize()
  18060. ], Node.prototype, "state", void 0);
  18061. __decorate([
  18062. BABYLON.serialize()
  18063. ], Node.prototype, "metadata", void 0);
  18064. return Node;
  18065. }());
  18066. BABYLON.Node = Node;
  18067. })(BABYLON || (BABYLON = {}));
  18068. //# sourceMappingURL=babylon.node.js.map
  18069. var BABYLON;
  18070. (function (BABYLON) {
  18071. var BoundingSphere = /** @class */ (function () {
  18072. /**
  18073. * Creates a new bounding sphere
  18074. * @param min defines the minimum vector (in local space)
  18075. * @param max defines the maximum vector (in local space)
  18076. */
  18077. function BoundingSphere(min, max) {
  18078. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18079. this.reConstruct(min, max);
  18080. }
  18081. /**
  18082. * Recreates the entire bounding sphere from scratch
  18083. * @param min defines the new minimum vector (in local space)
  18084. * @param max defines the new maximum vector (in local space)
  18085. */
  18086. BoundingSphere.prototype.reConstruct = function (min, max) {
  18087. this.minimum = min.clone();
  18088. this.maximum = max.clone();
  18089. var distance = BABYLON.Vector3.Distance(min, max);
  18090. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18091. this.radius = distance * 0.5;
  18092. this.centerWorld = BABYLON.Vector3.Zero();
  18093. this._update(BABYLON.Matrix.Identity());
  18094. };
  18095. // Methods
  18096. BoundingSphere.prototype._update = function (world) {
  18097. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18098. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18099. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18100. };
  18101. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18102. for (var i = 0; i < 6; i++) {
  18103. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18104. return false;
  18105. }
  18106. return true;
  18107. };
  18108. BoundingSphere.prototype.intersectsPoint = function (point) {
  18109. var x = this.centerWorld.x - point.x;
  18110. var y = this.centerWorld.y - point.y;
  18111. var z = this.centerWorld.z - point.z;
  18112. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18113. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18114. return false;
  18115. return true;
  18116. };
  18117. // Statics
  18118. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18119. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18120. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18121. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18122. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18123. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18124. return false;
  18125. return true;
  18126. };
  18127. return BoundingSphere;
  18128. }());
  18129. BABYLON.BoundingSphere = BoundingSphere;
  18130. })(BABYLON || (BABYLON = {}));
  18131. //# sourceMappingURL=babylon.boundingSphere.js.map
  18132. var BABYLON;
  18133. (function (BABYLON) {
  18134. var BoundingBox = /** @class */ (function () {
  18135. /**
  18136. * Creates a new bounding box
  18137. * @param min defines the minimum vector (in local space)
  18138. * @param max defines the maximum vector (in local space)
  18139. */
  18140. function BoundingBox(min, max) {
  18141. this.vectorsWorld = new Array();
  18142. this.reConstruct(min, max);
  18143. }
  18144. // Methods
  18145. /**
  18146. * Recreates the entire bounding box from scratch
  18147. * @param min defines the new minimum vector (in local space)
  18148. * @param max defines the new maximum vector (in local space)
  18149. */
  18150. BoundingBox.prototype.reConstruct = function (min, max) {
  18151. this.minimum = min.clone();
  18152. this.maximum = max.clone();
  18153. // Bounding vectors
  18154. this.vectors = new Array();
  18155. this.vectors.push(this.minimum.clone());
  18156. this.vectors.push(this.maximum.clone());
  18157. this.vectors.push(this.minimum.clone());
  18158. this.vectors[2].x = this.maximum.x;
  18159. this.vectors.push(this.minimum.clone());
  18160. this.vectors[3].y = this.maximum.y;
  18161. this.vectors.push(this.minimum.clone());
  18162. this.vectors[4].z = this.maximum.z;
  18163. this.vectors.push(this.maximum.clone());
  18164. this.vectors[5].z = this.minimum.z;
  18165. this.vectors.push(this.maximum.clone());
  18166. this.vectors[6].x = this.minimum.x;
  18167. this.vectors.push(this.maximum.clone());
  18168. this.vectors[7].y = this.minimum.y;
  18169. // OBB
  18170. this.center = this.maximum.add(this.minimum).scale(0.5);
  18171. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18172. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18173. // World
  18174. for (var index = 0; index < this.vectors.length; index++) {
  18175. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18176. }
  18177. this.minimumWorld = BABYLON.Vector3.Zero();
  18178. this.maximumWorld = BABYLON.Vector3.Zero();
  18179. this.centerWorld = BABYLON.Vector3.Zero();
  18180. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18181. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18182. };
  18183. BoundingBox.prototype.getWorldMatrix = function () {
  18184. return this._worldMatrix;
  18185. };
  18186. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18187. this._worldMatrix.copyFrom(matrix);
  18188. return this;
  18189. };
  18190. BoundingBox.prototype._update = function (world) {
  18191. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18192. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18193. for (var index = 0; index < this.vectors.length; index++) {
  18194. var v = this.vectorsWorld[index];
  18195. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18196. if (v.x < this.minimumWorld.x)
  18197. this.minimumWorld.x = v.x;
  18198. if (v.y < this.minimumWorld.y)
  18199. this.minimumWorld.y = v.y;
  18200. if (v.z < this.minimumWorld.z)
  18201. this.minimumWorld.z = v.z;
  18202. if (v.x > this.maximumWorld.x)
  18203. this.maximumWorld.x = v.x;
  18204. if (v.y > this.maximumWorld.y)
  18205. this.maximumWorld.y = v.y;
  18206. if (v.z > this.maximumWorld.z)
  18207. this.maximumWorld.z = v.z;
  18208. }
  18209. // Extend
  18210. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18211. this.extendSizeWorld.scaleInPlace(0.5);
  18212. // OBB
  18213. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18214. this.centerWorld.scaleInPlace(0.5);
  18215. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18216. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18217. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18218. this._worldMatrix = world;
  18219. };
  18220. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18221. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18222. };
  18223. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18224. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18225. };
  18226. BoundingBox.prototype.intersectsPoint = function (point) {
  18227. var delta = -BABYLON.Epsilon;
  18228. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18229. return false;
  18230. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18231. return false;
  18232. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18233. return false;
  18234. return true;
  18235. };
  18236. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18237. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18238. };
  18239. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18240. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18241. return false;
  18242. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18243. return false;
  18244. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18245. return false;
  18246. return true;
  18247. };
  18248. // Statics
  18249. BoundingBox.Intersects = function (box0, box1) {
  18250. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18251. return false;
  18252. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18253. return false;
  18254. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18255. return false;
  18256. return true;
  18257. };
  18258. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18259. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18260. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18261. return (num <= (sphereRadius * sphereRadius));
  18262. };
  18263. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18264. for (var p = 0; p < 6; p++) {
  18265. for (var i = 0; i < 8; i++) {
  18266. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18267. return false;
  18268. }
  18269. }
  18270. }
  18271. return true;
  18272. };
  18273. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18274. for (var p = 0; p < 6; p++) {
  18275. var inCount = 8;
  18276. for (var i = 0; i < 8; i++) {
  18277. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18278. --inCount;
  18279. }
  18280. else {
  18281. break;
  18282. }
  18283. }
  18284. if (inCount === 0)
  18285. return false;
  18286. }
  18287. return true;
  18288. };
  18289. return BoundingBox;
  18290. }());
  18291. BABYLON.BoundingBox = BoundingBox;
  18292. })(BABYLON || (BABYLON = {}));
  18293. //# sourceMappingURL=babylon.boundingBox.js.map
  18294. var BABYLON;
  18295. (function (BABYLON) {
  18296. var computeBoxExtents = function (axis, box) {
  18297. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18298. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18299. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18300. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18301. var r = r0 + r1 + r2;
  18302. return {
  18303. min: p - r,
  18304. max: p + r
  18305. };
  18306. };
  18307. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18308. var axisOverlap = function (axis, box0, box1) {
  18309. var result0 = computeBoxExtents(axis, box0);
  18310. var result1 = computeBoxExtents(axis, box1);
  18311. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18312. };
  18313. var BoundingInfo = /** @class */ (function () {
  18314. function BoundingInfo(minimum, maximum) {
  18315. this.minimum = minimum;
  18316. this.maximum = maximum;
  18317. this._isLocked = false;
  18318. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18319. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18320. }
  18321. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18322. get: function () {
  18323. return this._isLocked;
  18324. },
  18325. set: function (value) {
  18326. this._isLocked = value;
  18327. },
  18328. enumerable: true,
  18329. configurable: true
  18330. });
  18331. // Methods
  18332. BoundingInfo.prototype.update = function (world) {
  18333. if (this._isLocked) {
  18334. return;
  18335. }
  18336. this.boundingBox._update(world);
  18337. this.boundingSphere._update(world);
  18338. };
  18339. /**
  18340. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18341. * @param center New center of the bounding info
  18342. * @param extend New extend of the bounding info
  18343. */
  18344. BoundingInfo.prototype.centerOn = function (center, extend) {
  18345. this.minimum = center.subtract(extend);
  18346. this.maximum = center.add(extend);
  18347. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18348. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18349. return this;
  18350. };
  18351. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18352. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18353. return false;
  18354. return this.boundingBox.isInFrustum(frustumPlanes);
  18355. };
  18356. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18357. /**
  18358. * Gets the world distance between the min and max points of the bounding box
  18359. */
  18360. get: function () {
  18361. var boundingBox = this.boundingBox;
  18362. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18363. return size.length();
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18369. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18370. };
  18371. BoundingInfo.prototype._checkCollision = function (collider) {
  18372. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18373. };
  18374. BoundingInfo.prototype.intersectsPoint = function (point) {
  18375. if (!this.boundingSphere.centerWorld) {
  18376. return false;
  18377. }
  18378. if (!this.boundingSphere.intersectsPoint(point)) {
  18379. return false;
  18380. }
  18381. if (!this.boundingBox.intersectsPoint(point)) {
  18382. return false;
  18383. }
  18384. return true;
  18385. };
  18386. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18387. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18388. return false;
  18389. }
  18390. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18391. return false;
  18392. }
  18393. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18394. return false;
  18395. }
  18396. if (!precise) {
  18397. return true;
  18398. }
  18399. var box0 = this.boundingBox;
  18400. var box1 = boundingInfo.boundingBox;
  18401. if (!axisOverlap(box0.directions[0], box0, box1))
  18402. return false;
  18403. if (!axisOverlap(box0.directions[1], box0, box1))
  18404. return false;
  18405. if (!axisOverlap(box0.directions[2], box0, box1))
  18406. return false;
  18407. if (!axisOverlap(box1.directions[0], box0, box1))
  18408. return false;
  18409. if (!axisOverlap(box1.directions[1], box0, box1))
  18410. return false;
  18411. if (!axisOverlap(box1.directions[2], box0, box1))
  18412. return false;
  18413. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18414. return false;
  18415. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18416. return false;
  18417. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18418. return false;
  18419. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18420. return false;
  18421. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18422. return false;
  18423. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18424. return false;
  18425. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18426. return false;
  18427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18428. return false;
  18429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18430. return false;
  18431. return true;
  18432. };
  18433. return BoundingInfo;
  18434. }());
  18435. BABYLON.BoundingInfo = BoundingInfo;
  18436. })(BABYLON || (BABYLON = {}));
  18437. //# sourceMappingURL=babylon.boundingInfo.js.map
  18438. var BABYLON;
  18439. (function (BABYLON) {
  18440. var TransformNode = /** @class */ (function (_super) {
  18441. __extends(TransformNode, _super);
  18442. function TransformNode(name, scene, isPure) {
  18443. if (scene === void 0) { scene = null; }
  18444. if (isPure === void 0) { isPure = true; }
  18445. var _this = _super.call(this, name, scene) || this;
  18446. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18447. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18448. _this._up = new BABYLON.Vector3(0, 1, 0);
  18449. _this._right = new BABYLON.Vector3(1, 0, 0);
  18450. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18451. // Properties
  18452. _this._rotation = BABYLON.Vector3.Zero();
  18453. _this._scaling = BABYLON.Vector3.One();
  18454. _this._isDirty = false;
  18455. /**
  18456. * Set the billboard mode. Default is 0.
  18457. *
  18458. * | Value | Type | Description |
  18459. * | --- | --- | --- |
  18460. * | 0 | BILLBOARDMODE_NONE | |
  18461. * | 1 | BILLBOARDMODE_X | |
  18462. * | 2 | BILLBOARDMODE_Y | |
  18463. * | 4 | BILLBOARDMODE_Z | |
  18464. * | 7 | BILLBOARDMODE_ALL | |
  18465. *
  18466. */
  18467. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18468. _this.scalingDeterminant = 1;
  18469. _this.infiniteDistance = false;
  18470. /**
  18471. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18472. * By default the system will update normals to compensate
  18473. */
  18474. _this.ignoreNonUniformScaling = false;
  18475. _this.position = BABYLON.Vector3.Zero();
  18476. _this._localWorld = BABYLON.Matrix.Zero();
  18477. _this._worldMatrix = BABYLON.Matrix.Zero();
  18478. _this._worldMatrixDeterminant = 0;
  18479. _this._absolutePosition = BABYLON.Vector3.Zero();
  18480. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18481. _this._postMultiplyPivotMatrix = false;
  18482. _this._isWorldMatrixFrozen = false;
  18483. /**
  18484. * An event triggered after the world matrix is updated
  18485. */
  18486. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18487. _this._nonUniformScaling = false;
  18488. if (isPure) {
  18489. _this.getScene().addTransformNode(_this);
  18490. }
  18491. return _this;
  18492. }
  18493. /**
  18494. * Gets a string idenfifying the name of the class
  18495. * @returns "TransformNode" string
  18496. */
  18497. TransformNode.prototype.getClassName = function () {
  18498. return "TransformNode";
  18499. };
  18500. Object.defineProperty(TransformNode.prototype, "rotation", {
  18501. /**
  18502. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18503. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18504. * Default : (0.0, 0.0, 0.0)
  18505. */
  18506. get: function () {
  18507. return this._rotation;
  18508. },
  18509. set: function (newRotation) {
  18510. this._rotation = newRotation;
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(TransformNode.prototype, "scaling", {
  18516. /**
  18517. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18518. * Default : (1.0, 1.0, 1.0)
  18519. */
  18520. get: function () {
  18521. return this._scaling;
  18522. },
  18523. /**
  18524. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18525. * Default : (1.0, 1.0, 1.0)
  18526. */
  18527. set: function (newScaling) {
  18528. this._scaling = newScaling;
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18534. /**
  18535. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18536. * It's null by default.
  18537. * 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)
  18538. */
  18539. get: function () {
  18540. return this._rotationQuaternion;
  18541. },
  18542. set: function (quaternion) {
  18543. this._rotationQuaternion = quaternion;
  18544. //reset the rotation vector.
  18545. if (quaternion && this.rotation.length()) {
  18546. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18547. }
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. Object.defineProperty(TransformNode.prototype, "forward", {
  18553. /**
  18554. * The forward direction of that transform in world space.
  18555. */
  18556. get: function () {
  18557. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18558. },
  18559. enumerable: true,
  18560. configurable: true
  18561. });
  18562. Object.defineProperty(TransformNode.prototype, "up", {
  18563. /**
  18564. * The up direction of that transform in world space.
  18565. */
  18566. get: function () {
  18567. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. Object.defineProperty(TransformNode.prototype, "right", {
  18573. /**
  18574. * The right direction of that transform in world space.
  18575. */
  18576. get: function () {
  18577. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18578. },
  18579. enumerable: true,
  18580. configurable: true
  18581. });
  18582. /**
  18583. * Returns the latest update of the World matrix
  18584. * Returns a Matrix.
  18585. */
  18586. TransformNode.prototype.getWorldMatrix = function () {
  18587. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18588. this.computeWorldMatrix();
  18589. }
  18590. return this._worldMatrix;
  18591. };
  18592. /** @hidden */
  18593. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18594. return this._worldMatrixDeterminant;
  18595. };
  18596. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18597. /**
  18598. * Returns directly the latest state of the mesh World matrix.
  18599. * A Matrix is returned.
  18600. */
  18601. get: function () {
  18602. return this._worldMatrix;
  18603. },
  18604. enumerable: true,
  18605. configurable: true
  18606. });
  18607. /**
  18608. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18609. * Returns the TransformNode.
  18610. */
  18611. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18612. this._poseMatrix.copyFrom(matrix);
  18613. return this;
  18614. };
  18615. /**
  18616. * Returns the mesh Pose matrix.
  18617. * Returned object : Matrix
  18618. */
  18619. TransformNode.prototype.getPoseMatrix = function () {
  18620. return this._poseMatrix;
  18621. };
  18622. TransformNode.prototype._isSynchronized = function () {
  18623. if (this._isDirty) {
  18624. return false;
  18625. }
  18626. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18627. return false;
  18628. if (this._cache.pivotMatrixUpdated) {
  18629. return false;
  18630. }
  18631. if (this.infiniteDistance) {
  18632. return false;
  18633. }
  18634. if (!this._cache.position.equals(this.position))
  18635. return false;
  18636. if (this.rotationQuaternion) {
  18637. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18638. return false;
  18639. }
  18640. if (!this._cache.rotation.equals(this.rotation))
  18641. return false;
  18642. if (!this._cache.scaling.equals(this.scaling))
  18643. return false;
  18644. return true;
  18645. };
  18646. TransformNode.prototype._initCache = function () {
  18647. _super.prototype._initCache.call(this);
  18648. this._cache.localMatrixUpdated = false;
  18649. this._cache.position = BABYLON.Vector3.Zero();
  18650. this._cache.scaling = BABYLON.Vector3.Zero();
  18651. this._cache.rotation = BABYLON.Vector3.Zero();
  18652. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18653. this._cache.billboardMode = -1;
  18654. };
  18655. TransformNode.prototype.markAsDirty = function (property) {
  18656. if (property === "rotation") {
  18657. this.rotationQuaternion = null;
  18658. }
  18659. this._currentRenderId = Number.MAX_VALUE;
  18660. this._isDirty = true;
  18661. return this;
  18662. };
  18663. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18664. /**
  18665. * Returns the current mesh absolute position.
  18666. * Retuns a Vector3.
  18667. */
  18668. get: function () {
  18669. return this._absolutePosition;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. /**
  18675. * Sets a new matrix to apply before all other transformation
  18676. * @param matrix defines the transform matrix
  18677. * @returns the current TransformNode
  18678. */
  18679. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18680. return this.setPivotMatrix(matrix, false);
  18681. };
  18682. /**
  18683. * Sets a new pivot matrix to the current node
  18684. * @param matrix defines the new pivot matrix to use
  18685. * @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
  18686. * @returns the current TransformNode
  18687. */
  18688. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18689. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18690. this._pivotMatrix = matrix.clone();
  18691. this._cache.pivotMatrixUpdated = true;
  18692. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18693. if (this._postMultiplyPivotMatrix) {
  18694. if (!this._pivotMatrixInverse) {
  18695. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18696. }
  18697. else {
  18698. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18699. }
  18700. }
  18701. return this;
  18702. };
  18703. /**
  18704. * Returns the mesh pivot matrix.
  18705. * Default : Identity.
  18706. * A Matrix is returned.
  18707. */
  18708. TransformNode.prototype.getPivotMatrix = function () {
  18709. return this._pivotMatrix;
  18710. };
  18711. /**
  18712. * Prevents the World matrix to be computed any longer.
  18713. * Returns the TransformNode.
  18714. */
  18715. TransformNode.prototype.freezeWorldMatrix = function () {
  18716. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18717. this.computeWorldMatrix(true);
  18718. this._isWorldMatrixFrozen = true;
  18719. return this;
  18720. };
  18721. /**
  18722. * Allows back the World matrix computation.
  18723. * Returns the TransformNode.
  18724. */
  18725. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18726. this._isWorldMatrixFrozen = false;
  18727. this.computeWorldMatrix(true);
  18728. return this;
  18729. };
  18730. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18731. /**
  18732. * True if the World matrix has been frozen.
  18733. * Returns a boolean.
  18734. */
  18735. get: function () {
  18736. return this._isWorldMatrixFrozen;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. /**
  18742. * Retuns the mesh absolute position in the World.
  18743. * Returns a Vector3.
  18744. */
  18745. TransformNode.prototype.getAbsolutePosition = function () {
  18746. this.computeWorldMatrix();
  18747. return this._absolutePosition;
  18748. };
  18749. /**
  18750. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18751. * Returns the TransformNode.
  18752. */
  18753. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18754. if (!absolutePosition) {
  18755. return this;
  18756. }
  18757. var absolutePositionX;
  18758. var absolutePositionY;
  18759. var absolutePositionZ;
  18760. if (absolutePosition.x === undefined) {
  18761. if (arguments.length < 3) {
  18762. return this;
  18763. }
  18764. absolutePositionX = arguments[0];
  18765. absolutePositionY = arguments[1];
  18766. absolutePositionZ = arguments[2];
  18767. }
  18768. else {
  18769. absolutePositionX = absolutePosition.x;
  18770. absolutePositionY = absolutePosition.y;
  18771. absolutePositionZ = absolutePosition.z;
  18772. }
  18773. if (this.parent) {
  18774. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18775. invertParentWorldMatrix.invert();
  18776. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18777. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18778. }
  18779. else {
  18780. this.position.x = absolutePositionX;
  18781. this.position.y = absolutePositionY;
  18782. this.position.z = absolutePositionZ;
  18783. }
  18784. return this;
  18785. };
  18786. /**
  18787. * Sets the mesh position in its local space.
  18788. * Returns the TransformNode.
  18789. */
  18790. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18791. this.computeWorldMatrix();
  18792. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18793. return this;
  18794. };
  18795. /**
  18796. * Returns the mesh position in the local space from the current World matrix values.
  18797. * Returns a new Vector3.
  18798. */
  18799. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18800. this.computeWorldMatrix();
  18801. var invLocalWorldMatrix = this._localWorld.clone();
  18802. invLocalWorldMatrix.invert();
  18803. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18804. };
  18805. /**
  18806. * Translates the mesh along the passed Vector3 in its local space.
  18807. * Returns the TransformNode.
  18808. */
  18809. TransformNode.prototype.locallyTranslate = function (vector3) {
  18810. this.computeWorldMatrix(true);
  18811. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18812. return this;
  18813. };
  18814. /**
  18815. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18816. * @param targetPoint the position (must be in same space as current mesh) to look at
  18817. * @param yawCor optional yaw (y-axis) correction in radians
  18818. * @param pitchCor optional pitch (x-axis) correction in radians
  18819. * @param rollCor optional roll (z-axis) correction in radians
  18820. * @param space the choosen space of the target
  18821. * @returns the TransformNode.
  18822. */
  18823. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18824. if (yawCor === void 0) { yawCor = 0; }
  18825. if (pitchCor === void 0) { pitchCor = 0; }
  18826. if (rollCor === void 0) { rollCor = 0; }
  18827. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18828. var dv = TransformNode._lookAtVectorCache;
  18829. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18830. targetPoint.subtractToRef(pos, dv);
  18831. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18832. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18833. var pitch = Math.atan2(dv.y, len);
  18834. if (this.rotationQuaternion) {
  18835. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18836. }
  18837. else {
  18838. this.rotation.x = pitch + pitchCor;
  18839. this.rotation.y = yaw + yawCor;
  18840. this.rotation.z = rollCor;
  18841. }
  18842. return this;
  18843. };
  18844. /**
  18845. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18846. * This Vector3 is expressed in the World space.
  18847. */
  18848. TransformNode.prototype.getDirection = function (localAxis) {
  18849. var result = BABYLON.Vector3.Zero();
  18850. this.getDirectionToRef(localAxis, result);
  18851. return result;
  18852. };
  18853. /**
  18854. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18855. * localAxis is expressed in the mesh local space.
  18856. * result is computed in the Wordl space from the mesh World matrix.
  18857. * Returns the TransformNode.
  18858. */
  18859. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18860. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18861. return this;
  18862. };
  18863. /**
  18864. * Sets a new pivot point to the current node
  18865. * @param point defines the new pivot point to use
  18866. * @param space defines if the point is in world or local space (local by default)
  18867. * @returns the current TransformNode
  18868. */
  18869. TransformNode.prototype.setPivotPoint = function (point, space) {
  18870. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18871. if (this.getScene().getRenderId() == 0) {
  18872. this.computeWorldMatrix(true);
  18873. }
  18874. var wm = this.getWorldMatrix();
  18875. if (space == BABYLON.Space.WORLD) {
  18876. var tmat = BABYLON.Tmp.Matrix[0];
  18877. wm.invertToRef(tmat);
  18878. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18879. }
  18880. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18881. };
  18882. /**
  18883. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18884. */
  18885. TransformNode.prototype.getPivotPoint = function () {
  18886. var point = BABYLON.Vector3.Zero();
  18887. this.getPivotPointToRef(point);
  18888. return point;
  18889. };
  18890. /**
  18891. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18892. * Returns the TransformNode.
  18893. */
  18894. TransformNode.prototype.getPivotPointToRef = function (result) {
  18895. result.x = -this._pivotMatrix.m[12];
  18896. result.y = -this._pivotMatrix.m[13];
  18897. result.z = -this._pivotMatrix.m[14];
  18898. return this;
  18899. };
  18900. /**
  18901. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18902. */
  18903. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18904. var point = BABYLON.Vector3.Zero();
  18905. this.getAbsolutePivotPointToRef(point);
  18906. return point;
  18907. };
  18908. /**
  18909. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18910. * Returns the TransformNode.
  18911. */
  18912. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18913. result.x = this._pivotMatrix.m[12];
  18914. result.y = this._pivotMatrix.m[13];
  18915. result.z = this._pivotMatrix.m[14];
  18916. this.getPivotPointToRef(result);
  18917. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18918. return this;
  18919. };
  18920. /**
  18921. * Defines the passed node as the parent of the current node.
  18922. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18923. * Returns the TransformNode.
  18924. */
  18925. TransformNode.prototype.setParent = function (node) {
  18926. if (node === null) {
  18927. var rotation = BABYLON.Tmp.Quaternion[0];
  18928. var position = BABYLON.Tmp.Vector3[0];
  18929. var scale = BABYLON.Tmp.Vector3[1];
  18930. if (this.parent && this.parent.computeWorldMatrix) {
  18931. this.parent.computeWorldMatrix(true);
  18932. }
  18933. this.computeWorldMatrix(true);
  18934. this.getWorldMatrix().decompose(scale, rotation, position);
  18935. if (this.rotationQuaternion) {
  18936. this.rotationQuaternion.copyFrom(rotation);
  18937. }
  18938. else {
  18939. rotation.toEulerAnglesToRef(this.rotation);
  18940. }
  18941. this.scaling.x = scale.x;
  18942. this.scaling.y = scale.y;
  18943. this.scaling.z = scale.z;
  18944. this.position.x = position.x;
  18945. this.position.y = position.y;
  18946. this.position.z = position.z;
  18947. }
  18948. else {
  18949. var rotation = BABYLON.Tmp.Quaternion[0];
  18950. var position = BABYLON.Tmp.Vector3[0];
  18951. var scale = BABYLON.Tmp.Vector3[1];
  18952. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18953. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18954. this.computeWorldMatrix(true);
  18955. node.computeWorldMatrix(true);
  18956. node.getWorldMatrix().invertToRef(invParentMatrix);
  18957. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18958. diffMatrix.decompose(scale, rotation, position);
  18959. if (this.rotationQuaternion) {
  18960. this.rotationQuaternion.copyFrom(rotation);
  18961. }
  18962. else {
  18963. rotation.toEulerAnglesToRef(this.rotation);
  18964. }
  18965. this.position.x = position.x;
  18966. this.position.y = position.y;
  18967. this.position.z = position.z;
  18968. this.scaling.x = scale.x;
  18969. this.scaling.y = scale.y;
  18970. this.scaling.z = scale.z;
  18971. }
  18972. this.parent = node;
  18973. return this;
  18974. };
  18975. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18976. get: function () {
  18977. return this._nonUniformScaling;
  18978. },
  18979. enumerable: true,
  18980. configurable: true
  18981. });
  18982. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18983. if (this._nonUniformScaling === value) {
  18984. return false;
  18985. }
  18986. this._nonUniformScaling = value;
  18987. return true;
  18988. };
  18989. /**
  18990. * Attach the current TransformNode to another TransformNode associated with a bone
  18991. * @param bone Bone affecting the TransformNode
  18992. * @param affectedTransformNode TransformNode associated with the bone
  18993. */
  18994. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18995. this._transformToBoneReferal = affectedTransformNode;
  18996. this.parent = bone;
  18997. if (bone.getWorldMatrix().determinant() < 0) {
  18998. this.scalingDeterminant *= -1;
  18999. }
  19000. return this;
  19001. };
  19002. TransformNode.prototype.detachFromBone = function () {
  19003. if (!this.parent) {
  19004. return this;
  19005. }
  19006. if (this.parent.getWorldMatrix().determinant() < 0) {
  19007. this.scalingDeterminant *= -1;
  19008. }
  19009. this._transformToBoneReferal = null;
  19010. this.parent = null;
  19011. return this;
  19012. };
  19013. /**
  19014. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19015. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19016. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19017. * The passed axis is also normalized.
  19018. * Returns the TransformNode.
  19019. */
  19020. TransformNode.prototype.rotate = function (axis, amount, space) {
  19021. axis.normalize();
  19022. if (!this.rotationQuaternion) {
  19023. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19024. this.rotation = BABYLON.Vector3.Zero();
  19025. }
  19026. var rotationQuaternion;
  19027. if (!space || space === BABYLON.Space.LOCAL) {
  19028. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19029. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19030. }
  19031. else {
  19032. if (this.parent) {
  19033. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19034. invertParentWorldMatrix.invert();
  19035. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19036. }
  19037. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19038. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19039. }
  19040. return this;
  19041. };
  19042. /**
  19043. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19044. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19045. * The passed axis is also normalized.
  19046. * Returns the TransformNode.
  19047. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19048. */
  19049. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19050. axis.normalize();
  19051. if (!this.rotationQuaternion) {
  19052. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19053. this.rotation.copyFromFloats(0, 0, 0);
  19054. }
  19055. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19056. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19057. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19058. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19059. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19060. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19061. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19062. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19063. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19064. return this;
  19065. };
  19066. /**
  19067. * Translates the mesh along the axis vector for the passed distance in the given space.
  19068. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19069. * Returns the TransformNode.
  19070. */
  19071. TransformNode.prototype.translate = function (axis, distance, space) {
  19072. var displacementVector = axis.scale(distance);
  19073. if (!space || space === BABYLON.Space.LOCAL) {
  19074. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19075. this.setPositionWithLocalVector(tempV3);
  19076. }
  19077. else {
  19078. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19079. }
  19080. return this;
  19081. };
  19082. /**
  19083. * Adds a rotation step to the mesh current rotation.
  19084. * x, y, z are Euler angles expressed in radians.
  19085. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19086. * This means this rotation is made in the mesh local space only.
  19087. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19088. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19089. * ```javascript
  19090. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19091. * ```
  19092. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19093. * 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.
  19094. * Returns the TransformNode.
  19095. */
  19096. TransformNode.prototype.addRotation = function (x, y, z) {
  19097. var rotationQuaternion;
  19098. if (this.rotationQuaternion) {
  19099. rotationQuaternion = this.rotationQuaternion;
  19100. }
  19101. else {
  19102. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19103. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19104. }
  19105. var accumulation = BABYLON.Tmp.Quaternion[0];
  19106. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19107. rotationQuaternion.multiplyInPlace(accumulation);
  19108. if (!this.rotationQuaternion) {
  19109. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19110. }
  19111. return this;
  19112. };
  19113. /**
  19114. * Computes the mesh World matrix and returns it.
  19115. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19116. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19117. * If the parameter `force`is set to `true`, the actual computation is done.
  19118. * Returns the mesh World Matrix.
  19119. */
  19120. TransformNode.prototype.computeWorldMatrix = function (force) {
  19121. if (this._isWorldMatrixFrozen) {
  19122. return this._worldMatrix;
  19123. }
  19124. if (!force && this.isSynchronized(true)) {
  19125. this._currentRenderId = this.getScene().getRenderId();
  19126. return this._worldMatrix;
  19127. }
  19128. this._cache.position.copyFrom(this.position);
  19129. this._cache.scaling.copyFrom(this.scaling);
  19130. this._cache.pivotMatrixUpdated = false;
  19131. this._cache.billboardMode = this.billboardMode;
  19132. this._currentRenderId = this.getScene().getRenderId();
  19133. this._childRenderId = this.getScene().getRenderId();
  19134. this._isDirty = false;
  19135. // Scaling
  19136. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19137. // Rotation
  19138. //rotate, if quaternion is set and rotation was used
  19139. if (this.rotationQuaternion) {
  19140. var len = this.rotation.length();
  19141. if (len) {
  19142. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19143. this.rotation.copyFromFloats(0, 0, 0);
  19144. }
  19145. }
  19146. if (this.rotationQuaternion) {
  19147. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19148. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19149. }
  19150. else {
  19151. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19152. this._cache.rotation.copyFrom(this.rotation);
  19153. }
  19154. // Translation
  19155. var camera = this.getScene().activeCamera;
  19156. if (this.infiniteDistance && !this.parent && camera) {
  19157. var cameraWorldMatrix = camera.getWorldMatrix();
  19158. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19159. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19160. }
  19161. else {
  19162. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19163. }
  19164. // Composing transformations
  19165. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19166. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19167. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19168. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19169. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19170. // Need to decompose each rotation here
  19171. var currentPosition = BABYLON.Tmp.Vector3[3];
  19172. if (this.parent && this.parent.getWorldMatrix) {
  19173. if (this._transformToBoneReferal) {
  19174. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19175. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19176. }
  19177. else {
  19178. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19179. }
  19180. }
  19181. else {
  19182. currentPosition.copyFrom(this.position);
  19183. }
  19184. currentPosition.subtractInPlace(camera.globalPosition);
  19185. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19186. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19187. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19188. }
  19189. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19190. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19191. }
  19192. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19193. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19194. }
  19195. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19196. }
  19197. else {
  19198. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19199. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19200. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19201. }
  19202. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19203. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19204. }
  19205. // Local world
  19206. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19207. // Parent
  19208. if (this.parent && this.parent.getWorldMatrix) {
  19209. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19210. if (this._transformToBoneReferal) {
  19211. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19212. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19213. }
  19214. else {
  19215. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19216. }
  19217. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19218. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19219. this._worldMatrix.copyFrom(this._localWorld);
  19220. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19221. }
  19222. else {
  19223. if (this._transformToBoneReferal) {
  19224. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19225. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19226. }
  19227. else {
  19228. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19229. }
  19230. }
  19231. this._markSyncedWithParent();
  19232. }
  19233. else {
  19234. this._worldMatrix.copyFrom(this._localWorld);
  19235. }
  19236. // Post multiply inverse of pivotMatrix
  19237. if (this._postMultiplyPivotMatrix) {
  19238. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19239. }
  19240. // Normal matrix
  19241. if (!this.ignoreNonUniformScaling) {
  19242. if (this.scaling.isNonUniform) {
  19243. this._updateNonUniformScalingState(true);
  19244. }
  19245. else if (this.parent && this.parent._nonUniformScaling) {
  19246. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19247. }
  19248. else {
  19249. this._updateNonUniformScalingState(false);
  19250. }
  19251. }
  19252. else {
  19253. this._updateNonUniformScalingState(false);
  19254. }
  19255. this._afterComputeWorldMatrix();
  19256. // Absolute position
  19257. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19258. // Callbacks
  19259. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19260. if (!this._poseMatrix) {
  19261. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19262. }
  19263. // Cache the determinant
  19264. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19265. return this._worldMatrix;
  19266. };
  19267. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19268. };
  19269. /**
  19270. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19271. * @param func: callback function to add
  19272. *
  19273. * Returns the TransformNode.
  19274. */
  19275. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19276. this.onAfterWorldMatrixUpdateObservable.add(func);
  19277. return this;
  19278. };
  19279. /**
  19280. * Removes a registered callback function.
  19281. * Returns the TransformNode.
  19282. */
  19283. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19284. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19285. return this;
  19286. };
  19287. /**
  19288. * Clone the current transform node
  19289. * Returns the new transform node
  19290. * @param name Name of the new clone
  19291. * @param newParent New parent for the clone
  19292. * @param doNotCloneChildren Do not clone children hierarchy
  19293. */
  19294. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19295. var _this = this;
  19296. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19297. result.name = name;
  19298. result.id = name;
  19299. if (newParent) {
  19300. result.parent = newParent;
  19301. }
  19302. if (!doNotCloneChildren) {
  19303. // Children
  19304. var directDescendants = this.getDescendants(true);
  19305. for (var index = 0; index < directDescendants.length; index++) {
  19306. var child = directDescendants[index];
  19307. if (child.clone) {
  19308. child.clone(name + "." + child.name, result);
  19309. }
  19310. }
  19311. }
  19312. return result;
  19313. };
  19314. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19315. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19316. serializationObject.type = this.getClassName();
  19317. // Parent
  19318. if (this.parent) {
  19319. serializationObject.parentId = this.parent.id;
  19320. }
  19321. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19322. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19323. }
  19324. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19325. serializationObject.isEnabled = this.isEnabled();
  19326. // Parent
  19327. if (this.parent) {
  19328. serializationObject.parentId = this.parent.id;
  19329. }
  19330. return serializationObject;
  19331. };
  19332. // Statics
  19333. /**
  19334. * Returns a new TransformNode object parsed from the source provided.
  19335. * The parameter `parsedMesh` is the source.
  19336. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19337. */
  19338. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19339. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19340. if (BABYLON.Tags) {
  19341. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19342. }
  19343. if (parsedTransformNode.localMatrix) {
  19344. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19345. }
  19346. else if (parsedTransformNode.pivotMatrix) {
  19347. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19348. }
  19349. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19350. // Parent
  19351. if (parsedTransformNode.parentId) {
  19352. transformNode._waitingParentId = parsedTransformNode.parentId;
  19353. }
  19354. return transformNode;
  19355. };
  19356. /**
  19357. * Releases resources associated with this transform node.
  19358. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19359. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19360. */
  19361. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19362. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19363. // Animations
  19364. this.getScene().stopAnimation(this);
  19365. // Remove from scene
  19366. this.getScene().removeTransformNode(this);
  19367. this.onAfterWorldMatrixUpdateObservable.clear();
  19368. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19369. };
  19370. // Statics
  19371. TransformNode.BILLBOARDMODE_NONE = 0;
  19372. TransformNode.BILLBOARDMODE_X = 1;
  19373. TransformNode.BILLBOARDMODE_Y = 2;
  19374. TransformNode.BILLBOARDMODE_Z = 4;
  19375. TransformNode.BILLBOARDMODE_ALL = 7;
  19376. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19377. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19378. __decorate([
  19379. BABYLON.serializeAsVector3()
  19380. ], TransformNode.prototype, "_rotation", void 0);
  19381. __decorate([
  19382. BABYLON.serializeAsQuaternion()
  19383. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19384. __decorate([
  19385. BABYLON.serializeAsVector3()
  19386. ], TransformNode.prototype, "_scaling", void 0);
  19387. __decorate([
  19388. BABYLON.serialize()
  19389. ], TransformNode.prototype, "billboardMode", void 0);
  19390. __decorate([
  19391. BABYLON.serialize()
  19392. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19393. __decorate([
  19394. BABYLON.serialize()
  19395. ], TransformNode.prototype, "infiniteDistance", void 0);
  19396. __decorate([
  19397. BABYLON.serialize()
  19398. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19399. __decorate([
  19400. BABYLON.serializeAsVector3()
  19401. ], TransformNode.prototype, "position", void 0);
  19402. return TransformNode;
  19403. }(BABYLON.Node));
  19404. BABYLON.TransformNode = TransformNode;
  19405. })(BABYLON || (BABYLON = {}));
  19406. //# sourceMappingURL=babylon.transformNode.js.map
  19407. var BABYLON;
  19408. (function (BABYLON) {
  19409. /**
  19410. * Class used to store all common mesh properties
  19411. */
  19412. var AbstractMesh = /** @class */ (function (_super) {
  19413. __extends(AbstractMesh, _super);
  19414. // Constructor
  19415. /**
  19416. * Creates a new AbstractMesh
  19417. * @param name defines the name of the mesh
  19418. * @param scene defines the hosting scene
  19419. */
  19420. function AbstractMesh(name, scene) {
  19421. if (scene === void 0) { scene = null; }
  19422. var _this = _super.call(this, name, scene, false) || this;
  19423. _this._facetNb = 0; // facet number
  19424. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19425. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19426. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19427. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19428. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19429. _this._subDiv = {
  19430. max: 1,
  19431. X: 1,
  19432. Y: 1,
  19433. Z: 1
  19434. };
  19435. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19436. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19437. // Events
  19438. /**
  19439. * An event triggered when this mesh collides with another one
  19440. */
  19441. _this.onCollideObservable = new BABYLON.Observable();
  19442. /**
  19443. * An event triggered when the collision's position changes
  19444. */
  19445. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19446. /**
  19447. * An event triggered when material is changed
  19448. */
  19449. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19450. // Properties
  19451. /**
  19452. * Gets or sets the orientation for POV movement & rotation
  19453. */
  19454. _this.definedFacingForward = true;
  19455. /**
  19456. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19457. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19458. * * 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.
  19459. * @see http://doc.babylonjs.com/features/occlusionquery
  19460. */
  19461. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19462. /**
  19463. * 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:
  19464. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19465. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19466. * * 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.
  19467. * @see http://doc.babylonjs.com/features/occlusionquery
  19468. */
  19469. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19470. /**
  19471. * 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.
  19472. * The default value is -1 which means don't break the query and wait till the result
  19473. * @see http://doc.babylonjs.com/features/occlusionquery
  19474. */
  19475. _this.occlusionRetryCount = -1;
  19476. _this._occlusionInternalRetryCounter = 0;
  19477. _this._isOccluded = false;
  19478. _this._isOcclusionQueryInProgress = false;
  19479. _this._visibility = 1.0;
  19480. /** Gets or sets the alpha index used to sort transparent meshes
  19481. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19482. */
  19483. _this.alphaIndex = Number.MAX_VALUE;
  19484. /**
  19485. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19486. */
  19487. _this.isVisible = true;
  19488. /**
  19489. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19490. */
  19491. _this.isPickable = true;
  19492. /**
  19493. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19494. */
  19495. _this.showBoundingBox = false;
  19496. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19497. _this.showSubMeshesBoundingBox = false;
  19498. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19499. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19500. */
  19501. _this.isBlocker = false;
  19502. /**
  19503. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19504. */
  19505. _this.enablePointerMoveEvents = false;
  19506. /**
  19507. * Specifies the rendering group id for this mesh (0 by default)
  19508. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19509. */
  19510. _this.renderingGroupId = 0;
  19511. _this._receiveShadows = false;
  19512. /**
  19513. * Gets or sets a boolean indicating if the outline must be rendered as well
  19514. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19515. */
  19516. _this.renderOutline = false;
  19517. /** Defines color to use when rendering outline */
  19518. _this.outlineColor = BABYLON.Color3.Red();
  19519. /** Define width to use when rendering outline */
  19520. _this.outlineWidth = 0.02;
  19521. /**
  19522. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19523. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19524. */
  19525. _this.renderOverlay = false;
  19526. /** Defines color to use when rendering overlay */
  19527. _this.overlayColor = BABYLON.Color3.Red();
  19528. /** Defines alpha to use when rendering overlay */
  19529. _this.overlayAlpha = 0.5;
  19530. _this._hasVertexAlpha = false;
  19531. _this._useVertexColors = true;
  19532. _this._computeBonesUsingShaders = true;
  19533. _this._numBoneInfluencers = 4;
  19534. _this._applyFog = true;
  19535. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19536. _this.useOctreeForRenderingSelection = true;
  19537. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19538. _this.useOctreeForPicking = true;
  19539. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19540. _this.useOctreeForCollisions = true;
  19541. _this._layerMask = 0x0FFFFFFF;
  19542. /**
  19543. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19544. */
  19545. _this.alwaysSelectAsActiveMesh = false;
  19546. /**
  19547. * Gets or sets the current action manager
  19548. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19549. */
  19550. _this.actionManager = null;
  19551. /**
  19552. * Gets or sets impostor used for physic simulation
  19553. * @see http://doc.babylonjs.com/features/physics_engine
  19554. */
  19555. _this.physicsImpostor = null;
  19556. // Collisions
  19557. _this._checkCollisions = false;
  19558. _this._collisionMask = -1;
  19559. _this._collisionGroup = -1;
  19560. /**
  19561. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19562. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19563. */
  19564. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19565. /**
  19566. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19567. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19568. */
  19569. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19570. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19571. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19572. // Edges
  19573. /**
  19574. * Defines edge width used when edgesRenderer is enabled
  19575. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19576. */
  19577. _this.edgesWidth = 1;
  19578. /**
  19579. * Defines edge color used when edgesRenderer is enabled
  19580. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19581. */
  19582. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19583. // Cache
  19584. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19585. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19586. /** @hidden */
  19587. _this._renderId = 0;
  19588. /** @hidden */
  19589. _this._intersectionsInProgress = new Array();
  19590. /** @hidden */
  19591. _this._unIndexed = false;
  19592. /** @hidden */
  19593. _this._lightSources = new Array();
  19594. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19595. if (collidedMesh === void 0) { collidedMesh = null; }
  19596. //TODO move this to the collision coordinator!
  19597. if (_this.getScene().workerCollisions)
  19598. newPosition.multiplyInPlace(_this._collider._radius);
  19599. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19600. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19601. _this.position.addInPlace(_this._diffPositionForCollisions);
  19602. }
  19603. if (collidedMesh) {
  19604. _this.onCollideObservable.notifyObservers(collidedMesh);
  19605. }
  19606. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19607. };
  19608. _this.getScene().addMesh(_this);
  19609. _this._resyncLightSources();
  19610. return _this;
  19611. }
  19612. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19613. /**
  19614. * No billboard
  19615. */
  19616. get: function () {
  19617. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19623. /** Billboard on X axis */
  19624. get: function () {
  19625. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19631. /** Billboard on Y axis */
  19632. get: function () {
  19633. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19639. /** Billboard on Z axis */
  19640. get: function () {
  19641. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19647. /** Billboard on all axes */
  19648. get: function () {
  19649. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19655. /**
  19656. * Gets the number of facets in the mesh
  19657. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19658. */
  19659. get: function () {
  19660. return this._facetNb;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19666. /**
  19667. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19668. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19669. */
  19670. get: function () {
  19671. return this._partitioningSubdivisions;
  19672. },
  19673. set: function (nb) {
  19674. this._partitioningSubdivisions = nb;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19680. /**
  19681. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19682. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19683. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19684. */
  19685. get: function () {
  19686. return this._partitioningBBoxRatio;
  19687. },
  19688. set: function (ratio) {
  19689. this._partitioningBBoxRatio = ratio;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19695. /**
  19696. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19697. * Works only for updatable meshes.
  19698. * Doesn't work with multi-materials
  19699. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19700. */
  19701. get: function () {
  19702. return this._facetDepthSort;
  19703. },
  19704. set: function (sort) {
  19705. this._facetDepthSort = sort;
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19711. /**
  19712. * The location (Vector3) where the facet depth sort must be computed from.
  19713. * By default, the active camera position.
  19714. * Used only when facet depth sort is enabled
  19715. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19716. */
  19717. get: function () {
  19718. return this._facetDepthSortFrom;
  19719. },
  19720. set: function (location) {
  19721. this._facetDepthSortFrom = location;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19727. /**
  19728. * gets a boolean indicating if facetData is enabled
  19729. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19730. */
  19731. get: function () {
  19732. return this._facetDataEnabled;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. /** @hidden */
  19738. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19739. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19740. return false;
  19741. }
  19742. this._markSubMeshesAsMiscDirty();
  19743. return true;
  19744. };
  19745. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19746. /** Set a function to call when this mesh collides with another one */
  19747. set: function (callback) {
  19748. if (this._onCollideObserver) {
  19749. this.onCollideObservable.remove(this._onCollideObserver);
  19750. }
  19751. this._onCollideObserver = this.onCollideObservable.add(callback);
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19757. /** Set a function to call when the collision's position changes */
  19758. set: function (callback) {
  19759. if (this._onCollisionPositionChangeObserver) {
  19760. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19761. }
  19762. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19768. /**
  19769. * 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
  19770. * @see http://doc.babylonjs.com/features/occlusionquery
  19771. */
  19772. get: function () {
  19773. return this._isOccluded;
  19774. },
  19775. set: function (value) {
  19776. this._isOccluded = value;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19782. /**
  19783. * Flag to check the progress status of the query
  19784. * @see http://doc.babylonjs.com/features/occlusionquery
  19785. */
  19786. get: function () {
  19787. return this._isOcclusionQueryInProgress;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19793. /**
  19794. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19795. */
  19796. get: function () {
  19797. return this._visibility;
  19798. },
  19799. /**
  19800. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19801. */
  19802. set: function (value) {
  19803. if (this._visibility === value) {
  19804. return;
  19805. }
  19806. this._visibility = value;
  19807. this._markSubMeshesAsMiscDirty();
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(AbstractMesh.prototype, "material", {
  19813. /** Gets or sets current material */
  19814. get: function () {
  19815. return this._material;
  19816. },
  19817. set: function (value) {
  19818. if (this._material === value) {
  19819. return;
  19820. }
  19821. this._material = value;
  19822. if (this.onMaterialChangedObservable.hasObservers) {
  19823. this.onMaterialChangedObservable.notifyObservers(this);
  19824. }
  19825. if (!this.subMeshes) {
  19826. return;
  19827. }
  19828. this._unBindEffect();
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19834. /**
  19835. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19836. * @see http://doc.babylonjs.com/babylon101/shadows
  19837. */
  19838. get: function () {
  19839. return this._receiveShadows;
  19840. },
  19841. set: function (value) {
  19842. if (this._receiveShadows === value) {
  19843. return;
  19844. }
  19845. this._receiveShadows = value;
  19846. this._markSubMeshesAsLightDirty();
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19852. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19853. get: function () {
  19854. return this._hasVertexAlpha;
  19855. },
  19856. set: function (value) {
  19857. if (this._hasVertexAlpha === value) {
  19858. return;
  19859. }
  19860. this._hasVertexAlpha = value;
  19861. this._markSubMeshesAsAttributesDirty();
  19862. this._markSubMeshesAsMiscDirty();
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19868. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19869. get: function () {
  19870. return this._useVertexColors;
  19871. },
  19872. set: function (value) {
  19873. if (this._useVertexColors === value) {
  19874. return;
  19875. }
  19876. this._useVertexColors = value;
  19877. this._markSubMeshesAsAttributesDirty();
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19883. /**
  19884. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19885. */
  19886. get: function () {
  19887. return this._computeBonesUsingShaders;
  19888. },
  19889. set: function (value) {
  19890. if (this._computeBonesUsingShaders === value) {
  19891. return;
  19892. }
  19893. this._computeBonesUsingShaders = value;
  19894. this._markSubMeshesAsAttributesDirty();
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19900. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19901. get: function () {
  19902. return this._numBoneInfluencers;
  19903. },
  19904. set: function (value) {
  19905. if (this._numBoneInfluencers === value) {
  19906. return;
  19907. }
  19908. this._numBoneInfluencers = value;
  19909. this._markSubMeshesAsAttributesDirty();
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19915. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19916. get: function () {
  19917. return this._applyFog;
  19918. },
  19919. set: function (value) {
  19920. if (this._applyFog === value) {
  19921. return;
  19922. }
  19923. this._applyFog = value;
  19924. this._markSubMeshesAsMiscDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19930. /**
  19931. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19932. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19933. */
  19934. get: function () {
  19935. return this._layerMask;
  19936. },
  19937. set: function (value) {
  19938. if (value === this._layerMask) {
  19939. return;
  19940. }
  19941. this._layerMask = value;
  19942. this._resyncLightSources();
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19948. /**
  19949. * Gets or sets a collision mask used to mask collisions (default is -1).
  19950. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19951. */
  19952. get: function () {
  19953. return this._collisionMask;
  19954. },
  19955. set: function (mask) {
  19956. this._collisionMask = !isNaN(mask) ? mask : -1;
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19962. /**
  19963. * Gets or sets the current collision group mask (-1 by default).
  19964. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19965. */
  19966. get: function () {
  19967. return this._collisionGroup;
  19968. },
  19969. set: function (mask) {
  19970. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19976. /** @hidden */
  19977. get: function () {
  19978. return null;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19984. get: function () {
  19985. return this._skeleton;
  19986. },
  19987. /**
  19988. * Gets or sets a skeleton to apply skining transformations
  19989. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19990. */
  19991. set: function (value) {
  19992. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19993. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19994. }
  19995. if (value && value.needInitialSkinMatrix) {
  19996. value._registerMeshWithPoseMatrix(this);
  19997. }
  19998. this._skeleton = value;
  19999. if (!this._skeleton) {
  20000. this._bonesTransformMatrices = null;
  20001. }
  20002. this._markSubMeshesAsAttributesDirty();
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. /**
  20008. * Returns the string "AbstractMesh"
  20009. * @returns "AbstractMesh"
  20010. */
  20011. AbstractMesh.prototype.getClassName = function () {
  20012. return "AbstractMesh";
  20013. };
  20014. /**
  20015. * Gets a string representation of the current mesh
  20016. * @param fullDetails defines a boolean indicating if full details must be included
  20017. * @returns a string representation of the current mesh
  20018. */
  20019. AbstractMesh.prototype.toString = function (fullDetails) {
  20020. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20021. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20022. if (this._skeleton) {
  20023. ret += ", skeleton: " + this._skeleton.name;
  20024. }
  20025. if (fullDetails) {
  20026. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20027. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20028. }
  20029. return ret;
  20030. };
  20031. /** @hidden */
  20032. AbstractMesh.prototype._rebuild = function () {
  20033. if (this._occlusionQuery) {
  20034. this._occlusionQuery = null;
  20035. }
  20036. if (this._edgesRenderer) {
  20037. this._edgesRenderer._rebuild();
  20038. }
  20039. if (!this.subMeshes) {
  20040. return;
  20041. }
  20042. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20043. var subMesh = _a[_i];
  20044. subMesh._rebuild();
  20045. }
  20046. };
  20047. /** @hidden */
  20048. AbstractMesh.prototype._resyncLightSources = function () {
  20049. this._lightSources.length = 0;
  20050. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20051. var light = _a[_i];
  20052. if (!light.isEnabled()) {
  20053. continue;
  20054. }
  20055. if (light.canAffectMesh(this)) {
  20056. this._lightSources.push(light);
  20057. }
  20058. }
  20059. this._markSubMeshesAsLightDirty();
  20060. };
  20061. /** @hidden */
  20062. AbstractMesh.prototype._resyncLighSource = function (light) {
  20063. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20064. var index = this._lightSources.indexOf(light);
  20065. if (index === -1) {
  20066. if (!isIn) {
  20067. return;
  20068. }
  20069. this._lightSources.push(light);
  20070. }
  20071. else {
  20072. if (isIn) {
  20073. return;
  20074. }
  20075. this._lightSources.splice(index, 1);
  20076. }
  20077. this._markSubMeshesAsLightDirty();
  20078. };
  20079. /** @hidden */
  20080. AbstractMesh.prototype._unBindEffect = function () {
  20081. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20082. var subMesh = _a[_i];
  20083. subMesh.setEffect(null);
  20084. }
  20085. };
  20086. /** @hidden */
  20087. AbstractMesh.prototype._removeLightSource = function (light) {
  20088. var index = this._lightSources.indexOf(light);
  20089. if (index === -1) {
  20090. return;
  20091. }
  20092. this._lightSources.splice(index, 1);
  20093. this._markSubMeshesAsLightDirty();
  20094. };
  20095. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20096. if (!this.subMeshes) {
  20097. return;
  20098. }
  20099. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20100. var subMesh = _a[_i];
  20101. if (subMesh._materialDefines) {
  20102. func(subMesh._materialDefines);
  20103. }
  20104. }
  20105. };
  20106. /** @hidden */
  20107. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20108. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20109. };
  20110. /** @hidden */
  20111. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20112. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20116. if (!this.subMeshes) {
  20117. return;
  20118. }
  20119. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20120. var subMesh = _a[_i];
  20121. var material = subMesh.getMaterial();
  20122. if (material) {
  20123. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20124. }
  20125. }
  20126. };
  20127. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20128. /**
  20129. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20130. */
  20131. get: function () {
  20132. return this._scaling;
  20133. },
  20134. set: function (newScaling) {
  20135. this._scaling = newScaling;
  20136. if (this.physicsImpostor) {
  20137. this.physicsImpostor.forceUpdate();
  20138. }
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. // Methods
  20144. /**
  20145. * Disables the mesh edge rendering mode
  20146. * @returns the currentAbstractMesh
  20147. */
  20148. AbstractMesh.prototype.disableEdgesRendering = function () {
  20149. if (this._edgesRenderer) {
  20150. this._edgesRenderer.dispose();
  20151. this._edgesRenderer = null;
  20152. }
  20153. return this;
  20154. };
  20155. /**
  20156. * Enables the edge rendering mode on the mesh.
  20157. * This mode makes the mesh edges visible
  20158. * @param epsilon defines the maximal distance between two angles to detect a face
  20159. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20160. * @returns the currentAbstractMesh
  20161. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20162. */
  20163. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20164. if (epsilon === void 0) { epsilon = 0.95; }
  20165. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20166. this.disableEdgesRendering();
  20167. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20168. return this;
  20169. };
  20170. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20171. /**
  20172. * Gets the edgesRenderer associated with the mesh
  20173. */
  20174. get: function () {
  20175. return this._edgesRenderer;
  20176. },
  20177. enumerable: true,
  20178. configurable: true
  20179. });
  20180. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20181. /**
  20182. * Returns true if the mesh is blocked. Implemented by child classes
  20183. */
  20184. get: function () {
  20185. return false;
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. /**
  20191. * Returns the mesh itself by default. Implemented by child classes
  20192. * @param camera defines the camera to use to pick the right LOD level
  20193. * @returns the currentAbstractMesh
  20194. */
  20195. AbstractMesh.prototype.getLOD = function (camera) {
  20196. return this;
  20197. };
  20198. /**
  20199. * Returns 0 by default. Implemented by child classes
  20200. * @returns an integer
  20201. */
  20202. AbstractMesh.prototype.getTotalVertices = function () {
  20203. return 0;
  20204. };
  20205. /**
  20206. * Returns null by default. Implemented by child classes
  20207. * @returns null
  20208. */
  20209. AbstractMesh.prototype.getIndices = function () {
  20210. return null;
  20211. };
  20212. /**
  20213. * Returns the array of the requested vertex data kind. Implemented by child classes
  20214. * @param kind defines the vertex data kind to use
  20215. * @returns null
  20216. */
  20217. AbstractMesh.prototype.getVerticesData = function (kind) {
  20218. return null;
  20219. };
  20220. /**
  20221. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20222. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20223. * Note that a new underlying VertexBuffer object is created each call.
  20224. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20225. * @param kind defines vertex data kind:
  20226. * * BABYLON.VertexBuffer.PositionKind
  20227. * * BABYLON.VertexBuffer.UVKind
  20228. * * BABYLON.VertexBuffer.UV2Kind
  20229. * * BABYLON.VertexBuffer.UV3Kind
  20230. * * BABYLON.VertexBuffer.UV4Kind
  20231. * * BABYLON.VertexBuffer.UV5Kind
  20232. * * BABYLON.VertexBuffer.UV6Kind
  20233. * * BABYLON.VertexBuffer.ColorKind
  20234. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20235. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20236. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20237. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20238. * @param data defines the data source
  20239. * @param updatable defines if the data must be flagged as updatable (or static)
  20240. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20241. * @returns the current mesh
  20242. */
  20243. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20244. return this;
  20245. };
  20246. /**
  20247. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20248. * If the mesh has no geometry, it is simply returned as it is.
  20249. * @param kind defines vertex data kind:
  20250. * * BABYLON.VertexBuffer.PositionKind
  20251. * * BABYLON.VertexBuffer.UVKind
  20252. * * BABYLON.VertexBuffer.UV2Kind
  20253. * * BABYLON.VertexBuffer.UV3Kind
  20254. * * BABYLON.VertexBuffer.UV4Kind
  20255. * * BABYLON.VertexBuffer.UV5Kind
  20256. * * BABYLON.VertexBuffer.UV6Kind
  20257. * * BABYLON.VertexBuffer.ColorKind
  20258. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20259. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20260. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20261. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20262. * @param data defines the data source
  20263. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20264. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20265. * @returns the current mesh
  20266. */
  20267. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20268. return this;
  20269. };
  20270. /**
  20271. * Sets the mesh indices,
  20272. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20273. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20274. * @param totalVertices Defines the total number of vertices
  20275. * @returns the current mesh
  20276. */
  20277. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20278. return this;
  20279. };
  20280. /**
  20281. * Gets a boolean indicating if specific vertex data is present
  20282. * @param kind defines the vertex data kind to use
  20283. * @returns true is data kind is present
  20284. */
  20285. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20286. return false;
  20287. };
  20288. /**
  20289. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20290. * @returns a BoundingInfo
  20291. */
  20292. AbstractMesh.prototype.getBoundingInfo = function () {
  20293. if (this._masterMesh) {
  20294. return this._masterMesh.getBoundingInfo();
  20295. }
  20296. if (!this._boundingInfo) {
  20297. // this._boundingInfo is being created here
  20298. this._updateBoundingInfo();
  20299. }
  20300. // cannot be null.
  20301. return this._boundingInfo;
  20302. };
  20303. /**
  20304. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20305. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20306. * @returns the current mesh
  20307. */
  20308. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20309. if (includeDescendants === void 0) { includeDescendants = true; }
  20310. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20311. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20312. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20313. if (maxDimension === 0) {
  20314. return this;
  20315. }
  20316. var scale = 1 / maxDimension;
  20317. this.scaling.scaleInPlace(scale);
  20318. return this;
  20319. };
  20320. /**
  20321. * Overwrite the current bounding info
  20322. * @param boundingInfo defines the new bounding info
  20323. * @returns the current mesh
  20324. */
  20325. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20326. this._boundingInfo = boundingInfo;
  20327. return this;
  20328. };
  20329. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20330. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20331. get: function () {
  20332. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20333. },
  20334. enumerable: true,
  20335. configurable: true
  20336. });
  20337. /** @hidden */
  20338. AbstractMesh.prototype._preActivate = function () {
  20339. };
  20340. /** @hidden */
  20341. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20342. };
  20343. /** @hidden */
  20344. AbstractMesh.prototype._activate = function (renderId) {
  20345. this._renderId = renderId;
  20346. };
  20347. /**
  20348. * Gets the current world matrix
  20349. * @returns a Matrix
  20350. */
  20351. AbstractMesh.prototype.getWorldMatrix = function () {
  20352. if (this._masterMesh) {
  20353. return this._masterMesh.getWorldMatrix();
  20354. }
  20355. return _super.prototype.getWorldMatrix.call(this);
  20356. };
  20357. /** @hidden */
  20358. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20359. if (this._masterMesh) {
  20360. return this._masterMesh._getWorldMatrixDeterminant();
  20361. }
  20362. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20363. };
  20364. // ================================== Point of View Movement =================================
  20365. /**
  20366. * Perform relative position change from the point of view of behind the front of the mesh.
  20367. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20368. * Supports definition of mesh facing forward or backward
  20369. * @param amountRight defines the distance on the right axis
  20370. * @param amountUp defines the distance on the up axis
  20371. * @param amountForward defines the distance on the forward axis
  20372. * @returns the current mesh
  20373. */
  20374. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20375. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20376. return this;
  20377. };
  20378. /**
  20379. * Calculate relative position change from the point of view of behind the front of the mesh.
  20380. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20381. * Supports definition of mesh facing forward or backward
  20382. * @param amountRight defines the distance on the right axis
  20383. * @param amountUp defines the distance on the up axis
  20384. * @param amountForward defines the distance on the forward axis
  20385. * @returns the new displacement vector
  20386. */
  20387. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20388. var rotMatrix = new BABYLON.Matrix();
  20389. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20390. rotQuaternion.toRotationMatrix(rotMatrix);
  20391. var translationDelta = BABYLON.Vector3.Zero();
  20392. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20394. return translationDelta;
  20395. };
  20396. // ================================== Point of View Rotation =================================
  20397. /**
  20398. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20399. * Supports definition of mesh facing forward or backward
  20400. * @param flipBack defines the flip
  20401. * @param twirlClockwise defines the twirl
  20402. * @param tiltRight defines the tilt
  20403. * @returns the current mesh
  20404. */
  20405. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20406. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20407. return this;
  20408. };
  20409. /**
  20410. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20411. * Supports definition of mesh facing forward or backward.
  20412. * @param flipBack defines the flip
  20413. * @param twirlClockwise defines the twirl
  20414. * @param tiltRight defines the tilt
  20415. * @returns the new rotation vector
  20416. */
  20417. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20418. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20419. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20420. };
  20421. /**
  20422. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20423. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20424. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20425. * @returns the new bounding vectors
  20426. */
  20427. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20428. if (includeDescendants === void 0) { includeDescendants = true; }
  20429. if (predicate === void 0) { predicate = null; }
  20430. // Ensures that all world matrix will be recomputed.
  20431. this.getScene().incrementRenderId();
  20432. this.computeWorldMatrix(true);
  20433. var min;
  20434. var max;
  20435. var boundingInfo = this.getBoundingInfo();
  20436. if (!this.subMeshes) {
  20437. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20438. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20439. }
  20440. else {
  20441. min = boundingInfo.boundingBox.minimumWorld;
  20442. max = boundingInfo.boundingBox.maximumWorld;
  20443. }
  20444. if (includeDescendants) {
  20445. var descendants = this.getDescendants(false);
  20446. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20447. var descendant = descendants_1[_i];
  20448. var childMesh = descendant;
  20449. childMesh.computeWorldMatrix(true);
  20450. // Filters meshes based on custom predicate function.
  20451. if (predicate && !predicate(childMesh)) {
  20452. continue;
  20453. }
  20454. //make sure we have the needed params to get mix and max
  20455. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20456. continue;
  20457. }
  20458. var childBoundingInfo = childMesh.getBoundingInfo();
  20459. var boundingBox = childBoundingInfo.boundingBox;
  20460. var minBox = boundingBox.minimumWorld;
  20461. var maxBox = boundingBox.maximumWorld;
  20462. BABYLON.Tools.CheckExtends(minBox, min, max);
  20463. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20464. }
  20465. }
  20466. return {
  20467. min: min,
  20468. max: max
  20469. };
  20470. };
  20471. /** @hidden */
  20472. AbstractMesh.prototype._updateBoundingInfo = function () {
  20473. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20474. this._boundingInfo.update(this.worldMatrixFromCache);
  20475. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20476. return this;
  20477. };
  20478. /** @hidden */
  20479. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20480. if (!this.subMeshes) {
  20481. return this;
  20482. }
  20483. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20484. var subMesh = this.subMeshes[subIndex];
  20485. if (!subMesh.IsGlobal) {
  20486. subMesh.updateBoundingInfo(matrix);
  20487. }
  20488. }
  20489. return this;
  20490. };
  20491. /** @hidden */
  20492. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20493. // Bounding info
  20494. this._updateBoundingInfo();
  20495. };
  20496. /**
  20497. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20498. * A mesh is in the frustum if its bounding box intersects the frustum
  20499. * @param frustumPlanes defines the frustum to test
  20500. * @returns true if the mesh is in the frustum planes
  20501. */
  20502. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20503. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20504. };
  20505. /**
  20506. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20507. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20508. * @param frustumPlanes defines the frustum to test
  20509. * @returns true if the mesh is completely in the frustum planes
  20510. */
  20511. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20512. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20513. };
  20514. /**
  20515. * True if the mesh intersects another mesh or a SolidParticle object
  20516. * @param mesh defines a target mesh or SolidParticle to test
  20517. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20518. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20519. * @returns true if there is an intersection
  20520. */
  20521. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20522. if (precise === void 0) { precise = false; }
  20523. if (!this._boundingInfo || !mesh._boundingInfo) {
  20524. return false;
  20525. }
  20526. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20527. return true;
  20528. }
  20529. if (includeDescendants) {
  20530. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20531. var child = _a[_i];
  20532. if (child.intersectsMesh(mesh, precise, true)) {
  20533. return true;
  20534. }
  20535. }
  20536. }
  20537. return false;
  20538. };
  20539. /**
  20540. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20541. * @param point defines the point to test
  20542. * @returns true if there is an intersection
  20543. */
  20544. AbstractMesh.prototype.intersectsPoint = function (point) {
  20545. if (!this._boundingInfo) {
  20546. return false;
  20547. }
  20548. return this._boundingInfo.intersectsPoint(point);
  20549. };
  20550. /**
  20551. * Gets the current physics impostor
  20552. * @see http://doc.babylonjs.com/features/physics_engine
  20553. * @returns a physics impostor or null
  20554. */
  20555. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20556. return this.physicsImpostor;
  20557. };
  20558. /**
  20559. * Gets the position of the current mesh in camera space
  20560. * @param camera defines the camera to use
  20561. * @returns a position
  20562. */
  20563. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20564. if (camera === void 0) { camera = null; }
  20565. if (!camera) {
  20566. camera = this.getScene().activeCamera;
  20567. }
  20568. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20569. };
  20570. /**
  20571. * Returns the distance from the mesh to the active camera
  20572. * @param camera defines the camera to use
  20573. * @returns the distance
  20574. */
  20575. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20576. if (camera === void 0) { camera = null; }
  20577. if (!camera) {
  20578. camera = this.getScene().activeCamera;
  20579. }
  20580. return this.absolutePosition.subtract(camera.position).length();
  20581. };
  20582. /**
  20583. * Apply a physic impulse to the mesh
  20584. * @param force defines the force to apply
  20585. * @param contactPoint defines where to apply the force
  20586. * @returns the current mesh
  20587. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20588. */
  20589. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20590. if (!this.physicsImpostor) {
  20591. return this;
  20592. }
  20593. this.physicsImpostor.applyImpulse(force, contactPoint);
  20594. return this;
  20595. };
  20596. /**
  20597. * Creates a physic joint between two meshes
  20598. * @param otherMesh defines the other mesh to use
  20599. * @param pivot1 defines the pivot to use on this mesh
  20600. * @param pivot2 defines the pivot to use on the other mesh
  20601. * @param options defines additional options (can be plugin dependent)
  20602. * @returns the current mesh
  20603. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20604. */
  20605. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20606. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20607. return this;
  20608. }
  20609. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20610. mainPivot: pivot1,
  20611. connectedPivot: pivot2,
  20612. nativeParams: options
  20613. });
  20614. return this;
  20615. };
  20616. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20617. // Collisions
  20618. /**
  20619. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20620. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20621. */
  20622. get: function () {
  20623. return this._checkCollisions;
  20624. },
  20625. set: function (collisionEnabled) {
  20626. this._checkCollisions = collisionEnabled;
  20627. if (this.getScene().workerCollisions) {
  20628. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20629. }
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20635. /**
  20636. * Gets Collider object used to compute collisions (not physics)
  20637. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20638. */
  20639. get: function () {
  20640. return this._collider;
  20641. },
  20642. enumerable: true,
  20643. configurable: true
  20644. });
  20645. /**
  20646. * Move the mesh using collision engine
  20647. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20648. * @param displacement defines the requested displacement vector
  20649. * @returns the current mesh
  20650. */
  20651. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20652. var globalPosition = this.getAbsolutePosition();
  20653. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20654. if (!this._collider) {
  20655. this._collider = new BABYLON.Collider();
  20656. }
  20657. this._collider._radius = this.ellipsoid;
  20658. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20659. return this;
  20660. };
  20661. // Submeshes octree
  20662. /**
  20663. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20664. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20665. * @param maxCapacity defines the maximum size of each block (64 by default)
  20666. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20667. * @returns the new octree
  20668. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20669. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20670. */
  20671. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20672. if (maxCapacity === void 0) { maxCapacity = 64; }
  20673. if (maxDepth === void 0) { maxDepth = 2; }
  20674. if (!this._submeshesOctree) {
  20675. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20676. }
  20677. this.computeWorldMatrix(true);
  20678. var boundingInfo = this.getBoundingInfo();
  20679. // Update octree
  20680. var bbox = boundingInfo.boundingBox;
  20681. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20682. return this._submeshesOctree;
  20683. };
  20684. // Collisions
  20685. /** @hidden */
  20686. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20687. this._generatePointsArray();
  20688. if (!this._positions) {
  20689. return this;
  20690. }
  20691. // Transformation
  20692. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20693. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20694. subMesh._lastColliderWorldVertices = [];
  20695. subMesh._trianglePlanes = [];
  20696. var start = subMesh.verticesStart;
  20697. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20698. for (var i = start; i < end; i++) {
  20699. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20700. }
  20701. }
  20702. // Collide
  20703. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20704. if (collider.collisionFound) {
  20705. collider.collidedMesh = this;
  20706. }
  20707. return this;
  20708. };
  20709. /** @hidden */
  20710. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20711. var subMeshes;
  20712. var len;
  20713. // Octrees
  20714. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20715. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20716. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20717. len = intersections.length;
  20718. subMeshes = intersections.data;
  20719. }
  20720. else {
  20721. subMeshes = this.subMeshes;
  20722. len = subMeshes.length;
  20723. }
  20724. for (var index = 0; index < len; index++) {
  20725. var subMesh = subMeshes[index];
  20726. // Bounding test
  20727. if (len > 1 && !subMesh._checkCollision(collider))
  20728. continue;
  20729. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20730. }
  20731. return this;
  20732. };
  20733. /** @hidden */
  20734. AbstractMesh.prototype._checkCollision = function (collider) {
  20735. // Bounding box test
  20736. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20737. return this;
  20738. // Transformation matrix
  20739. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20740. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20741. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20742. return this;
  20743. };
  20744. // Picking
  20745. /** @hidden */
  20746. AbstractMesh.prototype._generatePointsArray = function () {
  20747. return false;
  20748. };
  20749. /**
  20750. * Checks if the passed Ray intersects with the mesh
  20751. * @param ray defines the ray to use
  20752. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20753. * @returns the picking info
  20754. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20755. */
  20756. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20757. var pickingInfo = new BABYLON.PickingInfo();
  20758. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20759. return pickingInfo;
  20760. }
  20761. if (!this._generatePointsArray()) {
  20762. return pickingInfo;
  20763. }
  20764. var intersectInfo = null;
  20765. // Octrees
  20766. var subMeshes;
  20767. var len;
  20768. if (this._submeshesOctree && this.useOctreeForPicking) {
  20769. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20770. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20771. len = intersections.length;
  20772. subMeshes = intersections.data;
  20773. }
  20774. else {
  20775. subMeshes = this.subMeshes;
  20776. len = subMeshes.length;
  20777. }
  20778. for (var index = 0; index < len; index++) {
  20779. var subMesh = subMeshes[index];
  20780. // Bounding test
  20781. if (len > 1 && !subMesh.canIntersects(ray))
  20782. continue;
  20783. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20784. if (currentIntersectInfo) {
  20785. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20786. intersectInfo = currentIntersectInfo;
  20787. intersectInfo.subMeshId = index;
  20788. if (fastCheck) {
  20789. break;
  20790. }
  20791. }
  20792. }
  20793. }
  20794. if (intersectInfo) {
  20795. // Get picked point
  20796. var world = this.getWorldMatrix();
  20797. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20798. var direction = ray.direction.clone();
  20799. direction = direction.scale(intersectInfo.distance);
  20800. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20801. var pickedPoint = worldOrigin.add(worldDirection);
  20802. // Return result
  20803. pickingInfo.hit = true;
  20804. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20805. pickingInfo.pickedPoint = pickedPoint;
  20806. pickingInfo.pickedMesh = this;
  20807. pickingInfo.bu = intersectInfo.bu || 0;
  20808. pickingInfo.bv = intersectInfo.bv || 0;
  20809. pickingInfo.faceId = intersectInfo.faceId;
  20810. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20811. return pickingInfo;
  20812. }
  20813. return pickingInfo;
  20814. };
  20815. /**
  20816. * Clones the current mesh
  20817. * @param name defines the mesh name
  20818. * @param newParent defines the new mesh parent
  20819. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20820. * @returns the new mesh
  20821. */
  20822. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20823. return null;
  20824. };
  20825. /**
  20826. * Disposes all the submeshes of the current meshnp
  20827. * @returns the current mesh
  20828. */
  20829. AbstractMesh.prototype.releaseSubMeshes = function () {
  20830. if (this.subMeshes) {
  20831. while (this.subMeshes.length) {
  20832. this.subMeshes[0].dispose();
  20833. }
  20834. }
  20835. else {
  20836. this.subMeshes = new Array();
  20837. }
  20838. return this;
  20839. };
  20840. /**
  20841. * Releases resources associated with this abstract mesh.
  20842. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20843. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20844. */
  20845. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20846. var _this = this;
  20847. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20848. var index;
  20849. // Smart Array Retainers.
  20850. this.getScene().freeActiveMeshes();
  20851. this.getScene().freeRenderingGroups();
  20852. // Action manager
  20853. if (this.actionManager !== undefined && this.actionManager !== null) {
  20854. this.actionManager.dispose();
  20855. this.actionManager = null;
  20856. }
  20857. // Skeleton
  20858. this._skeleton = null;
  20859. // Physics
  20860. if (this.physicsImpostor) {
  20861. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20862. }
  20863. // Intersections in progress
  20864. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20865. var other = this._intersectionsInProgress[index];
  20866. var pos = other._intersectionsInProgress.indexOf(this);
  20867. other._intersectionsInProgress.splice(pos, 1);
  20868. }
  20869. this._intersectionsInProgress = [];
  20870. // Lights
  20871. var lights = this.getScene().lights;
  20872. lights.forEach(function (light) {
  20873. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20874. if (meshIndex !== -1) {
  20875. light.includedOnlyMeshes.splice(meshIndex, 1);
  20876. }
  20877. meshIndex = light.excludedMeshes.indexOf(_this);
  20878. if (meshIndex !== -1) {
  20879. light.excludedMeshes.splice(meshIndex, 1);
  20880. }
  20881. // Shadow generators
  20882. var generator = light.getShadowGenerator();
  20883. if (generator) {
  20884. var shadowMap = generator.getShadowMap();
  20885. if (shadowMap && shadowMap.renderList) {
  20886. meshIndex = shadowMap.renderList.indexOf(_this);
  20887. if (meshIndex !== -1) {
  20888. shadowMap.renderList.splice(meshIndex, 1);
  20889. }
  20890. }
  20891. }
  20892. });
  20893. // Edges
  20894. if (this._edgesRenderer) {
  20895. this._edgesRenderer.dispose();
  20896. this._edgesRenderer = null;
  20897. }
  20898. // SubMeshes
  20899. if (this.getClassName() !== "InstancedMesh") {
  20900. this.releaseSubMeshes();
  20901. }
  20902. // Octree
  20903. var sceneOctree = this.getScene().selectionOctree;
  20904. if (sceneOctree !== undefined && sceneOctree !== null) {
  20905. var index = sceneOctree.dynamicContent.indexOf(this);
  20906. if (index !== -1) {
  20907. sceneOctree.dynamicContent.splice(index, 1);
  20908. }
  20909. }
  20910. // Query
  20911. var engine = this.getScene().getEngine();
  20912. if (this._occlusionQuery) {
  20913. this._isOcclusionQueryInProgress = false;
  20914. engine.deleteQuery(this._occlusionQuery);
  20915. this._occlusionQuery = null;
  20916. }
  20917. // Engine
  20918. engine.wipeCaches();
  20919. // Remove from scene
  20920. this.getScene().removeMesh(this);
  20921. if (disposeMaterialAndTextures) {
  20922. if (this.material) {
  20923. this.material.dispose(false, true);
  20924. }
  20925. }
  20926. if (!doNotRecurse) {
  20927. // Particles
  20928. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20929. if (this.getScene().particleSystems[index].emitter === this) {
  20930. this.getScene().particleSystems[index].dispose();
  20931. index--;
  20932. }
  20933. }
  20934. }
  20935. // facet data
  20936. if (this._facetDataEnabled) {
  20937. this.disableFacetData();
  20938. }
  20939. this.onAfterWorldMatrixUpdateObservable.clear();
  20940. this.onCollideObservable.clear();
  20941. this.onCollisionPositionChangeObservable.clear();
  20942. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20943. };
  20944. /**
  20945. * Adds the passed mesh as a child to the current mesh
  20946. * @param mesh defines the child mesh
  20947. * @returns the current mesh
  20948. */
  20949. AbstractMesh.prototype.addChild = function (mesh) {
  20950. mesh.setParent(this);
  20951. return this;
  20952. };
  20953. /**
  20954. * Removes the passed mesh from the current mesh children list
  20955. * @param mesh defines the child mesh
  20956. * @returns the current mesh
  20957. */
  20958. AbstractMesh.prototype.removeChild = function (mesh) {
  20959. mesh.setParent(null);
  20960. return this;
  20961. };
  20962. // Facet data
  20963. /** @hidden */
  20964. AbstractMesh.prototype._initFacetData = function () {
  20965. if (!this._facetNormals) {
  20966. this._facetNormals = new Array();
  20967. }
  20968. if (!this._facetPositions) {
  20969. this._facetPositions = new Array();
  20970. }
  20971. if (!this._facetPartitioning) {
  20972. this._facetPartitioning = new Array();
  20973. }
  20974. this._facetNb = (this.getIndices().length / 3) | 0;
  20975. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20976. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20977. for (var f = 0; f < this._facetNb; f++) {
  20978. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20979. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20980. }
  20981. this._facetDataEnabled = true;
  20982. return this;
  20983. };
  20984. /**
  20985. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20986. * This method can be called within the render loop.
  20987. * 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
  20988. * @returns the current mesh
  20989. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20990. */
  20991. AbstractMesh.prototype.updateFacetData = function () {
  20992. if (!this._facetDataEnabled) {
  20993. this._initFacetData();
  20994. }
  20995. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20996. var indices = this.getIndices();
  20997. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20998. var bInfo = this.getBoundingInfo();
  20999. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21000. // init arrays, matrix and sort function on first call
  21001. this._facetDepthSortEnabled = true;
  21002. if (indices instanceof Uint16Array) {
  21003. this._depthSortedIndices = new Uint16Array(indices);
  21004. }
  21005. else if (indices instanceof Uint32Array) {
  21006. this._depthSortedIndices = new Uint32Array(indices);
  21007. }
  21008. else {
  21009. var needs32bits = false;
  21010. for (var i = 0; i < indices.length; i++) {
  21011. if (indices[i] > 65535) {
  21012. needs32bits = true;
  21013. break;
  21014. }
  21015. }
  21016. if (needs32bits) {
  21017. this._depthSortedIndices = new Uint32Array(indices);
  21018. }
  21019. else {
  21020. this._depthSortedIndices = new Uint16Array(indices);
  21021. }
  21022. }
  21023. this._facetDepthSortFunction = function (f1, f2) {
  21024. return (f2.sqDistance - f1.sqDistance);
  21025. };
  21026. if (!this._facetDepthSortFrom) {
  21027. var camera = this.getScene().activeCamera;
  21028. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21029. }
  21030. this._depthSortedFacets = [];
  21031. for (var f = 0; f < this._facetNb; f++) {
  21032. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21033. this._depthSortedFacets.push(depthSortedFacet);
  21034. }
  21035. this._invertedMatrix = BABYLON.Matrix.Identity();
  21036. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21037. }
  21038. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21039. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21040. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21041. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21042. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21043. this._subDiv.max = this._partitioningSubdivisions;
  21044. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21045. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21046. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21047. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21048. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21049. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21050. // set the parameters for ComputeNormals()
  21051. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21052. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21053. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21054. this._facetParameters.bInfo = bInfo;
  21055. this._facetParameters.bbSize = this._bbSize;
  21056. this._facetParameters.subDiv = this._subDiv;
  21057. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21058. this._facetParameters.depthSort = this._facetDepthSort;
  21059. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21060. this.computeWorldMatrix(true);
  21061. this._worldMatrix.invertToRef(this._invertedMatrix);
  21062. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21063. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21064. }
  21065. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21066. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21067. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21068. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21069. var l = (this._depthSortedIndices.length / 3) | 0;
  21070. for (var f = 0; f < l; f++) {
  21071. var sind = this._depthSortedFacets[f].ind;
  21072. this._depthSortedIndices[f * 3] = indices[sind];
  21073. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21074. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21075. }
  21076. this.updateIndices(this._depthSortedIndices);
  21077. }
  21078. return this;
  21079. };
  21080. /**
  21081. * Returns the facetLocalNormals array.
  21082. * The normals are expressed in the mesh local spac
  21083. * @returns an array of Vector3
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21085. */
  21086. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21087. if (!this._facetNormals) {
  21088. this.updateFacetData();
  21089. }
  21090. return this._facetNormals;
  21091. };
  21092. /**
  21093. * Returns the facetLocalPositions array.
  21094. * The facet positions are expressed in the mesh local space
  21095. * @returns an array of Vector3
  21096. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21097. */
  21098. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21099. if (!this._facetPositions) {
  21100. this.updateFacetData();
  21101. }
  21102. return this._facetPositions;
  21103. };
  21104. /**
  21105. * Returns the facetLocalPartioning array
  21106. * @returns an array of array of numbers
  21107. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21108. */
  21109. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21110. if (!this._facetPartitioning) {
  21111. this.updateFacetData();
  21112. }
  21113. return this._facetPartitioning;
  21114. };
  21115. /**
  21116. * Returns the i-th facet position in the world system.
  21117. * This method allocates a new Vector3 per call
  21118. * @param i defines the facet index
  21119. * @returns a new Vector3
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21121. */
  21122. AbstractMesh.prototype.getFacetPosition = function (i) {
  21123. var pos = BABYLON.Vector3.Zero();
  21124. this.getFacetPositionToRef(i, pos);
  21125. return pos;
  21126. };
  21127. /**
  21128. * Sets the reference Vector3 with the i-th facet position in the world system
  21129. * @param i defines the facet index
  21130. * @param ref defines the target vector
  21131. * @returns the current mesh
  21132. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21133. */
  21134. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21135. var localPos = (this.getFacetLocalPositions())[i];
  21136. var world = this.getWorldMatrix();
  21137. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21138. return this;
  21139. };
  21140. /**
  21141. * Returns the i-th facet normal in the world system.
  21142. * This method allocates a new Vector3 per call
  21143. * @param i defines the facet index
  21144. * @returns a new Vector3
  21145. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21146. */
  21147. AbstractMesh.prototype.getFacetNormal = function (i) {
  21148. var norm = BABYLON.Vector3.Zero();
  21149. this.getFacetNormalToRef(i, norm);
  21150. return norm;
  21151. };
  21152. /**
  21153. * Sets the reference Vector3 with the i-th facet normal in the world system
  21154. * @param i defines the facet index
  21155. * @param ref defines the target vector
  21156. * @returns the current mesh
  21157. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21158. */
  21159. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21160. var localNorm = (this.getFacetLocalNormals())[i];
  21161. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21162. return this;
  21163. };
  21164. /**
  21165. * 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)
  21166. * @param x defines x coordinate
  21167. * @param y defines y coordinate
  21168. * @param z defines z coordinate
  21169. * @returns the array of facet indexes
  21170. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21171. */
  21172. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21173. var bInfo = this.getBoundingInfo();
  21174. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21175. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21176. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21177. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21178. return null;
  21179. }
  21180. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21181. };
  21182. /**
  21183. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21184. * @param projected sets as the (x,y,z) world projection on the facet
  21185. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21186. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21187. * @param x defines x coordinate
  21188. * @param y defines y coordinate
  21189. * @param z defines z coordinate
  21190. * @returns the face index if found (or null instead)
  21191. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21192. */
  21193. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21194. if (checkFace === void 0) { checkFace = false; }
  21195. if (facing === void 0) { facing = true; }
  21196. var world = this.getWorldMatrix();
  21197. var invMat = BABYLON.Tmp.Matrix[5];
  21198. world.invertToRef(invMat);
  21199. var invVect = BABYLON.Tmp.Vector3[8];
  21200. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21201. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21202. if (projected) {
  21203. // tranform the local computed projected vector to world coordinates
  21204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21205. }
  21206. return closest;
  21207. };
  21208. /**
  21209. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21210. * @param projected sets as the (x,y,z) local projection on the facet
  21211. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21212. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21213. * @param x defines x coordinate
  21214. * @param y defines y coordinate
  21215. * @param z defines z coordinate
  21216. * @returns the face index if found (or null instead)
  21217. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21218. */
  21219. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21220. if (checkFace === void 0) { checkFace = false; }
  21221. if (facing === void 0) { facing = true; }
  21222. var closest = null;
  21223. var tmpx = 0.0;
  21224. var tmpy = 0.0;
  21225. var tmpz = 0.0;
  21226. var d = 0.0; // tmp dot facet normal * facet position
  21227. var t0 = 0.0;
  21228. var projx = 0.0;
  21229. var projy = 0.0;
  21230. var projz = 0.0;
  21231. // Get all the facets in the same partitioning block than (x, y, z)
  21232. var facetPositions = this.getFacetLocalPositions();
  21233. var facetNormals = this.getFacetLocalNormals();
  21234. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21235. if (!facetsInBlock) {
  21236. return null;
  21237. }
  21238. // Get the closest facet to (x, y, z)
  21239. var shortest = Number.MAX_VALUE; // init distance vars
  21240. var tmpDistance = shortest;
  21241. var fib; // current facet in the block
  21242. var norm; // current facet normal
  21243. var p0; // current facet barycenter position
  21244. // loop on all the facets in the current partitioning block
  21245. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21246. fib = facetsInBlock[idx];
  21247. norm = facetNormals[fib];
  21248. p0 = facetPositions[fib];
  21249. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21250. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21251. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21252. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21253. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21254. projx = x + norm.x * t0;
  21255. projy = y + norm.y * t0;
  21256. projz = z + norm.z * t0;
  21257. tmpx = projx - x;
  21258. tmpy = projy - y;
  21259. tmpz = projz - z;
  21260. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21261. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21262. shortest = tmpDistance;
  21263. closest = fib;
  21264. if (projected) {
  21265. projected.x = projx;
  21266. projected.y = projy;
  21267. projected.z = projz;
  21268. }
  21269. }
  21270. }
  21271. }
  21272. return closest;
  21273. };
  21274. /**
  21275. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21276. * @returns the parameters
  21277. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21278. */
  21279. AbstractMesh.prototype.getFacetDataParameters = function () {
  21280. return this._facetParameters;
  21281. };
  21282. /**
  21283. * Disables the feature FacetData and frees the related memory
  21284. * @returns the current mesh
  21285. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21286. */
  21287. AbstractMesh.prototype.disableFacetData = function () {
  21288. if (this._facetDataEnabled) {
  21289. this._facetDataEnabled = false;
  21290. this._facetPositions = new Array();
  21291. this._facetNormals = new Array();
  21292. this._facetPartitioning = new Array();
  21293. this._facetParameters = null;
  21294. this._depthSortedIndices = new Uint32Array(0);
  21295. }
  21296. return this;
  21297. };
  21298. /**
  21299. * Updates the AbstractMesh indices array
  21300. * @param indices defines the data source
  21301. * @returns the current mesh
  21302. */
  21303. AbstractMesh.prototype.updateIndices = function (indices) {
  21304. return this;
  21305. };
  21306. /**
  21307. * Creates new normals data for the mesh
  21308. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21309. * @returns the current mesh
  21310. */
  21311. AbstractMesh.prototype.createNormals = function (updatable) {
  21312. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21313. var indices = this.getIndices();
  21314. var normals;
  21315. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21316. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21317. }
  21318. else {
  21319. normals = [];
  21320. }
  21321. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21322. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21323. return this;
  21324. };
  21325. /**
  21326. * Align the mesh with a normal
  21327. * @param normal defines the normal to use
  21328. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21329. * @returns the current mesh
  21330. */
  21331. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21332. if (!upDirection) {
  21333. upDirection = BABYLON.Axis.Y;
  21334. }
  21335. var axisX = BABYLON.Tmp.Vector3[0];
  21336. var axisZ = BABYLON.Tmp.Vector3[1];
  21337. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21338. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21339. if (this.rotationQuaternion) {
  21340. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21341. }
  21342. else {
  21343. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21344. }
  21345. return this;
  21346. };
  21347. /** @hidden */
  21348. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21349. var engine = this.getEngine();
  21350. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21351. this._isOccluded = false;
  21352. return;
  21353. }
  21354. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21355. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21356. if (isOcclusionQueryAvailable) {
  21357. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21358. this._isOcclusionQueryInProgress = false;
  21359. this._occlusionInternalRetryCounter = 0;
  21360. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21361. }
  21362. else {
  21363. this._occlusionInternalRetryCounter++;
  21364. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21365. this._isOcclusionQueryInProgress = false;
  21366. this._occlusionInternalRetryCounter = 0;
  21367. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21368. // if strict continue the last state of the object.
  21369. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21370. }
  21371. else {
  21372. return;
  21373. }
  21374. }
  21375. }
  21376. var scene = this.getScene();
  21377. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21378. if (!this._occlusionQuery) {
  21379. this._occlusionQuery = engine.createQuery();
  21380. }
  21381. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21382. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21383. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21384. this._isOcclusionQueryInProgress = true;
  21385. };
  21386. /** No occlusion */
  21387. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21388. /** Occlusion set to optimisitic */
  21389. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21390. /** Occlusion set to strict */
  21391. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21392. /** Use an accurante occlusion algorithm */
  21393. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21394. /** Use a conservative occlusion algorithm */
  21395. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21396. return AbstractMesh;
  21397. }(BABYLON.TransformNode));
  21398. BABYLON.AbstractMesh = AbstractMesh;
  21399. })(BABYLON || (BABYLON = {}));
  21400. //# sourceMappingURL=babylon.abstractMesh.js.map
  21401. var BABYLON;
  21402. (function (BABYLON) {
  21403. /**
  21404. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21405. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21406. * 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.
  21407. */
  21408. var Light = /** @class */ (function (_super) {
  21409. __extends(Light, _super);
  21410. /**
  21411. * Creates a Light object in the scene.
  21412. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21413. * @param name The firendly name of the light
  21414. * @param scene The scene the light belongs too
  21415. */
  21416. function Light(name, scene) {
  21417. var _this = _super.call(this, name, scene) || this;
  21418. /**
  21419. * Diffuse gives the basic color to an object.
  21420. */
  21421. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21422. /**
  21423. * Specular produces a highlight color on an object.
  21424. * Note: This is note affecting PBR materials.
  21425. */
  21426. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21427. /**
  21428. * Strength of the light.
  21429. * Note: By default it is define in the framework own unit.
  21430. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21431. */
  21432. _this.intensity = 1.0;
  21433. /**
  21434. * Defines how far from the source the light is impacting in scene units.
  21435. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21436. */
  21437. _this.range = Number.MAX_VALUE;
  21438. /**
  21439. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21440. * of light.
  21441. */
  21442. _this._photometricScale = 1.0;
  21443. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21444. _this._radius = 0.00001;
  21445. /**
  21446. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21447. * exceeding the number allowed of the materials.
  21448. */
  21449. _this.renderPriority = 0;
  21450. _this._shadowEnabled = true;
  21451. _this._excludeWithLayerMask = 0;
  21452. _this._includeOnlyWithLayerMask = 0;
  21453. _this._lightmapMode = 0;
  21454. /**
  21455. * @hidden Internal use only.
  21456. */
  21457. _this._excludedMeshesIds = new Array();
  21458. /**
  21459. * @hidden Internal use only.
  21460. */
  21461. _this._includedOnlyMeshesIds = new Array();
  21462. _this.getScene().addLight(_this);
  21463. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21464. _this._buildUniformLayout();
  21465. _this.includedOnlyMeshes = new Array();
  21466. _this.excludedMeshes = new Array();
  21467. _this._resyncMeshes();
  21468. return _this;
  21469. }
  21470. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21471. /**
  21472. * If every light affecting the material is in this lightmapMode,
  21473. * material.lightmapTexture adds or multiplies
  21474. * (depends on material.useLightmapAsShadowmap)
  21475. * after every other light calculations.
  21476. */
  21477. get: function () {
  21478. return Light._LIGHTMAP_DEFAULT;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21484. /**
  21485. * material.lightmapTexture as only diffuse lighting from this light
  21486. * adds only specular lighting from this light
  21487. * adds dynamic shadows
  21488. */
  21489. get: function () {
  21490. return Light._LIGHTMAP_SPECULAR;
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21496. /**
  21497. * material.lightmapTexture as only lighting
  21498. * no light calculation from this light
  21499. * only adds dynamic shadows from this light
  21500. */
  21501. get: function () {
  21502. return Light._LIGHTMAP_SHADOWSONLY;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21508. /**
  21509. * Each light type uses the default quantity according to its type:
  21510. * point/spot lights use luminous intensity
  21511. * directional lights use illuminance
  21512. */
  21513. get: function () {
  21514. return Light._INTENSITYMODE_AUTOMATIC;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21520. /**
  21521. * lumen (lm)
  21522. */
  21523. get: function () {
  21524. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21530. /**
  21531. * candela (lm/sr)
  21532. */
  21533. get: function () {
  21534. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21540. /**
  21541. * lux (lm/m^2)
  21542. */
  21543. get: function () {
  21544. return Light._INTENSITYMODE_ILLUMINANCE;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21550. /**
  21551. * nit (cd/m^2)
  21552. */
  21553. get: function () {
  21554. return Light._INTENSITYMODE_LUMINANCE;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21560. /**
  21561. * Light type const id of the point light.
  21562. */
  21563. get: function () {
  21564. return Light._LIGHTTYPEID_POINTLIGHT;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21570. /**
  21571. * Light type const id of the directional light.
  21572. */
  21573. get: function () {
  21574. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21580. /**
  21581. * Light type const id of the spot light.
  21582. */
  21583. get: function () {
  21584. return Light._LIGHTTYPEID_SPOTLIGHT;
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21590. /**
  21591. * Light type const id of the hemispheric light.
  21592. */
  21593. get: function () {
  21594. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. Object.defineProperty(Light.prototype, "intensityMode", {
  21600. /**
  21601. * Gets the photometric scale used to interpret the intensity.
  21602. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21603. */
  21604. get: function () {
  21605. return this._intensityMode;
  21606. },
  21607. /**
  21608. * Sets the photometric scale used to interpret the intensity.
  21609. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21610. */
  21611. set: function (value) {
  21612. this._intensityMode = value;
  21613. this._computePhotometricScale();
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. ;
  21619. ;
  21620. Object.defineProperty(Light.prototype, "radius", {
  21621. /**
  21622. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21623. */
  21624. get: function () {
  21625. return this._radius;
  21626. },
  21627. /**
  21628. * sets the light radius used by PBR Materials to simulate soft area lights.
  21629. */
  21630. set: function (value) {
  21631. this._radius = value;
  21632. this._computePhotometricScale();
  21633. },
  21634. enumerable: true,
  21635. configurable: true
  21636. });
  21637. ;
  21638. ;
  21639. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21640. /**
  21641. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21642. * the current shadow generator.
  21643. */
  21644. get: function () {
  21645. return this._shadowEnabled;
  21646. },
  21647. /**
  21648. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21649. * the current shadow generator.
  21650. */
  21651. set: function (value) {
  21652. if (this._shadowEnabled === value) {
  21653. return;
  21654. }
  21655. this._shadowEnabled = value;
  21656. this._markMeshesAsLightDirty();
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21662. /**
  21663. * Gets the only meshes impacted by this light.
  21664. */
  21665. get: function () {
  21666. return this._includedOnlyMeshes;
  21667. },
  21668. /**
  21669. * Sets the only meshes impacted by this light.
  21670. */
  21671. set: function (value) {
  21672. this._includedOnlyMeshes = value;
  21673. this._hookArrayForIncludedOnly(value);
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21679. /**
  21680. * Gets the meshes not impacted by this light.
  21681. */
  21682. get: function () {
  21683. return this._excludedMeshes;
  21684. },
  21685. /**
  21686. * Sets the meshes not impacted by this light.
  21687. */
  21688. set: function (value) {
  21689. this._excludedMeshes = value;
  21690. this._hookArrayForExcluded(value);
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21696. /**
  21697. * Gets the layer id use to find what meshes are not impacted by the light.
  21698. * Inactive if 0
  21699. */
  21700. get: function () {
  21701. return this._excludeWithLayerMask;
  21702. },
  21703. /**
  21704. * Sets the layer id use to find what meshes are not impacted by the light.
  21705. * Inactive if 0
  21706. */
  21707. set: function (value) {
  21708. this._excludeWithLayerMask = value;
  21709. this._resyncMeshes();
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21715. /**
  21716. * Gets the layer id use to find what meshes are impacted by the light.
  21717. * Inactive if 0
  21718. */
  21719. get: function () {
  21720. return this._includeOnlyWithLayerMask;
  21721. },
  21722. /**
  21723. * Sets the layer id use to find what meshes are impacted by the light.
  21724. * Inactive if 0
  21725. */
  21726. set: function (value) {
  21727. this._includeOnlyWithLayerMask = value;
  21728. this._resyncMeshes();
  21729. },
  21730. enumerable: true,
  21731. configurable: true
  21732. });
  21733. Object.defineProperty(Light.prototype, "lightmapMode", {
  21734. /**
  21735. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21736. */
  21737. get: function () {
  21738. return this._lightmapMode;
  21739. },
  21740. /**
  21741. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21742. */
  21743. set: function (value) {
  21744. if (this._lightmapMode === value) {
  21745. return;
  21746. }
  21747. this._lightmapMode = value;
  21748. this._markMeshesAsLightDirty();
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. /**
  21754. * Returns the string "Light".
  21755. * @returns the class name
  21756. */
  21757. Light.prototype.getClassName = function () {
  21758. return "Light";
  21759. };
  21760. /**
  21761. * Converts the light information to a readable string for debug purpose.
  21762. * @param fullDetails Supports for multiple levels of logging within scene loading
  21763. * @returns the human readable light info
  21764. */
  21765. Light.prototype.toString = function (fullDetails) {
  21766. var ret = "Name: " + this.name;
  21767. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21768. if (this.animations) {
  21769. for (var i = 0; i < this.animations.length; i++) {
  21770. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21771. }
  21772. }
  21773. if (fullDetails) {
  21774. }
  21775. return ret;
  21776. };
  21777. /**
  21778. * Set the enabled state of this node.
  21779. * @param value - the new enabled state
  21780. */
  21781. Light.prototype.setEnabled = function (value) {
  21782. _super.prototype.setEnabled.call(this, value);
  21783. this._resyncMeshes();
  21784. };
  21785. /**
  21786. * Returns the Light associated shadow generator if any.
  21787. * @return the associated shadow generator.
  21788. */
  21789. Light.prototype.getShadowGenerator = function () {
  21790. return this._shadowGenerator;
  21791. };
  21792. /**
  21793. * Returns a Vector3, the absolute light position in the World.
  21794. * @returns the world space position of the light
  21795. */
  21796. Light.prototype.getAbsolutePosition = function () {
  21797. return BABYLON.Vector3.Zero();
  21798. };
  21799. /**
  21800. * Specifies if the light will affect the passed mesh.
  21801. * @param mesh The mesh to test against the light
  21802. * @return true the mesh is affected otherwise, false.
  21803. */
  21804. Light.prototype.canAffectMesh = function (mesh) {
  21805. if (!mesh) {
  21806. return true;
  21807. }
  21808. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21809. return false;
  21810. }
  21811. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21812. return false;
  21813. }
  21814. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21815. return false;
  21816. }
  21817. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21818. return false;
  21819. }
  21820. return true;
  21821. };
  21822. /**
  21823. * Computes and Returns the light World matrix.
  21824. * @returns the world matrix
  21825. */
  21826. Light.prototype.getWorldMatrix = function () {
  21827. this._currentRenderId = this.getScene().getRenderId();
  21828. this._childRenderId = this._currentRenderId;
  21829. var worldMatrix = this._getWorldMatrix();
  21830. if (this.parent && this.parent.getWorldMatrix) {
  21831. if (!this._parentedWorldMatrix) {
  21832. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21833. }
  21834. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21835. this._markSyncedWithParent();
  21836. return this._parentedWorldMatrix;
  21837. }
  21838. return worldMatrix;
  21839. };
  21840. /**
  21841. * Sort function to order lights for rendering.
  21842. * @param a First Light object to compare to second.
  21843. * @param b Second Light object to compare first.
  21844. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21845. */
  21846. Light.CompareLightsPriority = function (a, b) {
  21847. //shadow-casting lights have priority over non-shadow-casting lights
  21848. //the renderPrioirty is a secondary sort criterion
  21849. if (a.shadowEnabled !== b.shadowEnabled) {
  21850. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21851. }
  21852. return b.renderPriority - a.renderPriority;
  21853. };
  21854. /**
  21855. * Releases resources associated with this node.
  21856. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21857. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21858. */
  21859. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21860. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21861. if (this._shadowGenerator) {
  21862. this._shadowGenerator.dispose();
  21863. this._shadowGenerator = null;
  21864. }
  21865. // Animations
  21866. this.getScene().stopAnimation(this);
  21867. // Remove from meshes
  21868. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21869. var mesh = _a[_i];
  21870. mesh._removeLightSource(this);
  21871. }
  21872. this._uniformBuffer.dispose();
  21873. // Remove from scene
  21874. this.getScene().removeLight(this);
  21875. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21876. };
  21877. /**
  21878. * Returns the light type ID (integer).
  21879. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21880. */
  21881. Light.prototype.getTypeID = function () {
  21882. return 0;
  21883. };
  21884. /**
  21885. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21886. * @returns the scaled intensity in intensity mode unit
  21887. */
  21888. Light.prototype.getScaledIntensity = function () {
  21889. return this._photometricScale * this.intensity;
  21890. };
  21891. /**
  21892. * Returns a new Light object, named "name", from the current one.
  21893. * @param name The name of the cloned light
  21894. * @returns the new created light
  21895. */
  21896. Light.prototype.clone = function (name) {
  21897. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21898. if (!constructor) {
  21899. return null;
  21900. }
  21901. return BABYLON.SerializationHelper.Clone(constructor, this);
  21902. };
  21903. /**
  21904. * Serializes the current light into a Serialization object.
  21905. * @returns the serialized object.
  21906. */
  21907. Light.prototype.serialize = function () {
  21908. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21909. // Type
  21910. serializationObject.type = this.getTypeID();
  21911. // Parent
  21912. if (this.parent) {
  21913. serializationObject.parentId = this.parent.id;
  21914. }
  21915. // Inclusion / exclusions
  21916. if (this.excludedMeshes.length > 0) {
  21917. serializationObject.excludedMeshesIds = [];
  21918. this.excludedMeshes.forEach(function (mesh) {
  21919. serializationObject.excludedMeshesIds.push(mesh.id);
  21920. });
  21921. }
  21922. if (this.includedOnlyMeshes.length > 0) {
  21923. serializationObject.includedOnlyMeshesIds = [];
  21924. this.includedOnlyMeshes.forEach(function (mesh) {
  21925. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21926. });
  21927. }
  21928. // Animations
  21929. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21930. serializationObject.ranges = this.serializeAnimationRanges();
  21931. return serializationObject;
  21932. };
  21933. /**
  21934. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21935. * This new light is named "name" and added to the passed scene.
  21936. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21937. * @param name The friendly name of the light
  21938. * @param scene The scene the new light will belong to
  21939. * @returns the constructor function
  21940. */
  21941. Light.GetConstructorFromName = function (type, name, scene) {
  21942. switch (type) {
  21943. case 0:
  21944. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21945. case 1:
  21946. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21947. case 2:
  21948. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21949. case 3:
  21950. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21951. }
  21952. return null;
  21953. };
  21954. /**
  21955. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21956. * @param parsedLight The JSON representation of the light
  21957. * @param scene The scene to create the parsed light in
  21958. * @returns the created light after parsing
  21959. */
  21960. Light.Parse = function (parsedLight, scene) {
  21961. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21962. if (!constructor) {
  21963. return null;
  21964. }
  21965. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21966. // Inclusion / exclusions
  21967. if (parsedLight.excludedMeshesIds) {
  21968. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21969. }
  21970. if (parsedLight.includedOnlyMeshesIds) {
  21971. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21972. }
  21973. // Parent
  21974. if (parsedLight.parentId) {
  21975. light._waitingParentId = parsedLight.parentId;
  21976. }
  21977. // Animations
  21978. if (parsedLight.animations) {
  21979. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21980. var parsedAnimation = parsedLight.animations[animationIndex];
  21981. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21982. }
  21983. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21984. }
  21985. if (parsedLight.autoAnimate) {
  21986. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21987. }
  21988. return light;
  21989. };
  21990. Light.prototype._hookArrayForExcluded = function (array) {
  21991. var _this = this;
  21992. var oldPush = array.push;
  21993. array.push = function () {
  21994. var items = [];
  21995. for (var _i = 0; _i < arguments.length; _i++) {
  21996. items[_i] = arguments[_i];
  21997. }
  21998. var result = oldPush.apply(array, items);
  21999. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22000. var item = items_1[_a];
  22001. item._resyncLighSource(_this);
  22002. }
  22003. return result;
  22004. };
  22005. var oldSplice = array.splice;
  22006. array.splice = function (index, deleteCount) {
  22007. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22008. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22009. var item = deleted_1[_i];
  22010. item._resyncLighSource(_this);
  22011. }
  22012. return deleted;
  22013. };
  22014. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22015. var item = array_1[_i];
  22016. item._resyncLighSource(this);
  22017. }
  22018. };
  22019. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22020. var _this = this;
  22021. var oldPush = array.push;
  22022. array.push = function () {
  22023. var items = [];
  22024. for (var _i = 0; _i < arguments.length; _i++) {
  22025. items[_i] = arguments[_i];
  22026. }
  22027. var result = oldPush.apply(array, items);
  22028. _this._resyncMeshes();
  22029. return result;
  22030. };
  22031. var oldSplice = array.splice;
  22032. array.splice = function (index, deleteCount) {
  22033. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22034. _this._resyncMeshes();
  22035. return deleted;
  22036. };
  22037. this._resyncMeshes();
  22038. };
  22039. Light.prototype._resyncMeshes = function () {
  22040. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22041. var mesh = _a[_i];
  22042. mesh._resyncLighSource(this);
  22043. }
  22044. };
  22045. /**
  22046. * Forces the meshes to update their light related information in their rendering used effects
  22047. * @hidden Internal Use Only
  22048. */
  22049. Light.prototype._markMeshesAsLightDirty = function () {
  22050. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22051. var mesh = _a[_i];
  22052. if (mesh._lightSources.indexOf(this) !== -1) {
  22053. mesh._markSubMeshesAsLightDirty();
  22054. }
  22055. }
  22056. };
  22057. /**
  22058. * Recomputes the cached photometric scale if needed.
  22059. */
  22060. Light.prototype._computePhotometricScale = function () {
  22061. this._photometricScale = this._getPhotometricScale();
  22062. this.getScene().resetCachedMaterial();
  22063. };
  22064. /**
  22065. * Returns the Photometric Scale according to the light type and intensity mode.
  22066. */
  22067. Light.prototype._getPhotometricScale = function () {
  22068. var photometricScale = 0.0;
  22069. var lightTypeID = this.getTypeID();
  22070. //get photometric mode
  22071. var photometricMode = this.intensityMode;
  22072. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22073. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22074. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22075. }
  22076. else {
  22077. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22078. }
  22079. }
  22080. //compute photometric scale
  22081. switch (lightTypeID) {
  22082. case Light.LIGHTTYPEID_POINTLIGHT:
  22083. case Light.LIGHTTYPEID_SPOTLIGHT:
  22084. switch (photometricMode) {
  22085. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22086. photometricScale = 1.0 / (4.0 * Math.PI);
  22087. break;
  22088. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22089. photometricScale = 1.0;
  22090. break;
  22091. case Light.INTENSITYMODE_LUMINANCE:
  22092. photometricScale = this.radius * this.radius;
  22093. break;
  22094. }
  22095. break;
  22096. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22097. switch (photometricMode) {
  22098. case Light.INTENSITYMODE_ILLUMINANCE:
  22099. photometricScale = 1.0;
  22100. break;
  22101. case Light.INTENSITYMODE_LUMINANCE:
  22102. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22103. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22104. var apexAngleRadians = this.radius;
  22105. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22106. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22107. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22108. photometricScale = solidAngle;
  22109. break;
  22110. }
  22111. break;
  22112. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22113. // No fall off in hemisperic light.
  22114. photometricScale = 1.0;
  22115. break;
  22116. }
  22117. return photometricScale;
  22118. };
  22119. /**
  22120. * Reorder the light in the scene according to their defined priority.
  22121. * @hidden Internal Use Only
  22122. */
  22123. Light.prototype._reorderLightsInScene = function () {
  22124. var scene = this.getScene();
  22125. if (this._renderPriority != 0) {
  22126. scene.requireLightSorting = true;
  22127. }
  22128. this.getScene().sortLightsByPriority();
  22129. };
  22130. //lightmapMode Consts
  22131. Light._LIGHTMAP_DEFAULT = 0;
  22132. Light._LIGHTMAP_SPECULAR = 1;
  22133. Light._LIGHTMAP_SHADOWSONLY = 2;
  22134. // Intensity Mode Consts
  22135. Light._INTENSITYMODE_AUTOMATIC = 0;
  22136. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22137. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22138. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22139. Light._INTENSITYMODE_LUMINANCE = 4;
  22140. // Light types ids const.
  22141. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22142. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22143. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22144. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22145. __decorate([
  22146. BABYLON.serializeAsColor3()
  22147. ], Light.prototype, "diffuse", void 0);
  22148. __decorate([
  22149. BABYLON.serializeAsColor3()
  22150. ], Light.prototype, "specular", void 0);
  22151. __decorate([
  22152. BABYLON.serialize()
  22153. ], Light.prototype, "intensity", void 0);
  22154. __decorate([
  22155. BABYLON.serialize()
  22156. ], Light.prototype, "range", void 0);
  22157. __decorate([
  22158. BABYLON.serialize()
  22159. ], Light.prototype, "intensityMode", null);
  22160. __decorate([
  22161. BABYLON.serialize()
  22162. ], Light.prototype, "radius", null);
  22163. __decorate([
  22164. BABYLON.serialize()
  22165. ], Light.prototype, "_renderPriority", void 0);
  22166. __decorate([
  22167. BABYLON.expandToProperty("_reorderLightsInScene")
  22168. ], Light.prototype, "renderPriority", void 0);
  22169. __decorate([
  22170. BABYLON.serialize("shadowEnabled")
  22171. ], Light.prototype, "_shadowEnabled", void 0);
  22172. __decorate([
  22173. BABYLON.serialize("excludeWithLayerMask")
  22174. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22175. __decorate([
  22176. BABYLON.serialize("includeOnlyWithLayerMask")
  22177. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22178. __decorate([
  22179. BABYLON.serialize("lightmapMode")
  22180. ], Light.prototype, "_lightmapMode", void 0);
  22181. return Light;
  22182. }(BABYLON.Node));
  22183. BABYLON.Light = Light;
  22184. })(BABYLON || (BABYLON = {}));
  22185. //# sourceMappingURL=babylon.light.js.map
  22186. var BABYLON;
  22187. (function (BABYLON) {
  22188. var Camera = /** @class */ (function (_super) {
  22189. __extends(Camera, _super);
  22190. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22191. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22192. var _this = _super.call(this, name, scene) || this;
  22193. /**
  22194. * The vector the camera should consider as up.
  22195. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22196. */
  22197. _this.upVector = BABYLON.Vector3.Up();
  22198. _this.orthoLeft = null;
  22199. _this.orthoRight = null;
  22200. _this.orthoBottom = null;
  22201. _this.orthoTop = null;
  22202. /**
  22203. * FOV is set in Radians. (default is 0.8)
  22204. */
  22205. _this.fov = 0.8;
  22206. _this.minZ = 1;
  22207. _this.maxZ = 10000.0;
  22208. _this.inertia = 0.9;
  22209. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22210. _this.isIntermediate = false;
  22211. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22212. /**
  22213. * Restricts the camera to viewing objects with the same layerMask.
  22214. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22215. */
  22216. _this.layerMask = 0x0FFFFFFF;
  22217. /**
  22218. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22219. */
  22220. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22221. // Camera rig members
  22222. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22223. _this._rigCameras = new Array();
  22224. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22225. _this._skipRendering = false;
  22226. _this.customRenderTargets = new Array();
  22227. // Observables
  22228. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22229. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22230. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22231. _this.onRestoreStateObservable = new BABYLON.Observable();
  22232. // Cache
  22233. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22234. _this._projectionMatrix = new BABYLON.Matrix();
  22235. _this._doNotComputeProjectionMatrix = false;
  22236. _this._worldMatrix = BABYLON.Matrix.Identity();
  22237. _this._postProcesses = new Array();
  22238. _this._transformMatrix = BABYLON.Matrix.Zero();
  22239. _this._activeMeshes = new BABYLON.SmartArray(256);
  22240. _this._globalPosition = BABYLON.Vector3.Zero();
  22241. _this._refreshFrustumPlanes = true;
  22242. _this.getScene().addCamera(_this);
  22243. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22244. _this.getScene().activeCamera = _this;
  22245. }
  22246. _this.position = position;
  22247. return _this;
  22248. }
  22249. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22250. get: function () {
  22251. return Camera._PERSPECTIVE_CAMERA;
  22252. },
  22253. enumerable: true,
  22254. configurable: true
  22255. });
  22256. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22257. get: function () {
  22258. return Camera._ORTHOGRAPHIC_CAMERA;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22264. /**
  22265. * This is the default FOV mode for perspective cameras.
  22266. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22267. *
  22268. */
  22269. get: function () {
  22270. return Camera._FOVMODE_VERTICAL_FIXED;
  22271. },
  22272. enumerable: true,
  22273. configurable: true
  22274. });
  22275. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22276. /**
  22277. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22278. *
  22279. */
  22280. get: function () {
  22281. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22287. get: function () {
  22288. return Camera._RIG_MODE_NONE;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22294. get: function () {
  22295. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22301. get: function () {
  22302. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22308. get: function () {
  22309. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22310. },
  22311. enumerable: true,
  22312. configurable: true
  22313. });
  22314. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22315. get: function () {
  22316. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22317. },
  22318. enumerable: true,
  22319. configurable: true
  22320. });
  22321. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22322. get: function () {
  22323. return Camera._RIG_MODE_VR;
  22324. },
  22325. enumerable: true,
  22326. configurable: true
  22327. });
  22328. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22329. get: function () {
  22330. return Camera._RIG_MODE_WEBVR;
  22331. },
  22332. enumerable: true,
  22333. configurable: true
  22334. });
  22335. /**
  22336. * Store current camera state (fov, position, etc..)
  22337. */
  22338. Camera.prototype.storeState = function () {
  22339. this._stateStored = true;
  22340. this._storedFov = this.fov;
  22341. return this;
  22342. };
  22343. /**
  22344. * Restores the camera state values if it has been stored. You must call storeState() first
  22345. */
  22346. Camera.prototype._restoreStateValues = function () {
  22347. if (!this._stateStored) {
  22348. return false;
  22349. }
  22350. this.fov = this._storedFov;
  22351. return true;
  22352. };
  22353. /**
  22354. * Restored camera state. You must call storeState() first
  22355. */
  22356. Camera.prototype.restoreState = function () {
  22357. if (this._restoreStateValues()) {
  22358. this.onRestoreStateObservable.notifyObservers(this);
  22359. return true;
  22360. }
  22361. return false;
  22362. };
  22363. Camera.prototype.getClassName = function () {
  22364. return "Camera";
  22365. };
  22366. /**
  22367. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22368. */
  22369. Camera.prototype.toString = function (fullDetails) {
  22370. var ret = "Name: " + this.name;
  22371. ret += ", type: " + this.getClassName();
  22372. if (this.animations) {
  22373. for (var i = 0; i < this.animations.length; i++) {
  22374. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22375. }
  22376. }
  22377. if (fullDetails) {
  22378. }
  22379. return ret;
  22380. };
  22381. Object.defineProperty(Camera.prototype, "globalPosition", {
  22382. get: function () {
  22383. return this._globalPosition;
  22384. },
  22385. enumerable: true,
  22386. configurable: true
  22387. });
  22388. Camera.prototype.getActiveMeshes = function () {
  22389. return this._activeMeshes;
  22390. };
  22391. Camera.prototype.isActiveMesh = function (mesh) {
  22392. return (this._activeMeshes.indexOf(mesh) !== -1);
  22393. };
  22394. /**
  22395. * Is this camera ready to be used/rendered
  22396. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22397. * @return true if the camera is ready
  22398. */
  22399. Camera.prototype.isReady = function (completeCheck) {
  22400. if (completeCheck === void 0) { completeCheck = false; }
  22401. if (completeCheck) {
  22402. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22403. var pp = _a[_i];
  22404. if (pp && !pp.isReady()) {
  22405. return false;
  22406. }
  22407. }
  22408. }
  22409. return _super.prototype.isReady.call(this, completeCheck);
  22410. };
  22411. //Cache
  22412. Camera.prototype._initCache = function () {
  22413. _super.prototype._initCache.call(this);
  22414. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22415. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22416. this._cache.mode = undefined;
  22417. this._cache.minZ = undefined;
  22418. this._cache.maxZ = undefined;
  22419. this._cache.fov = undefined;
  22420. this._cache.fovMode = undefined;
  22421. this._cache.aspectRatio = undefined;
  22422. this._cache.orthoLeft = undefined;
  22423. this._cache.orthoRight = undefined;
  22424. this._cache.orthoBottom = undefined;
  22425. this._cache.orthoTop = undefined;
  22426. this._cache.renderWidth = undefined;
  22427. this._cache.renderHeight = undefined;
  22428. };
  22429. Camera.prototype._updateCache = function (ignoreParentClass) {
  22430. if (!ignoreParentClass) {
  22431. _super.prototype._updateCache.call(this);
  22432. }
  22433. this._cache.position.copyFrom(this.position);
  22434. this._cache.upVector.copyFrom(this.upVector);
  22435. };
  22436. // Synchronized
  22437. Camera.prototype._isSynchronized = function () {
  22438. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22439. };
  22440. Camera.prototype._isSynchronizedViewMatrix = function () {
  22441. if (!_super.prototype._isSynchronized.call(this))
  22442. return false;
  22443. return this._cache.position.equals(this.position)
  22444. && this._cache.upVector.equals(this.upVector)
  22445. && this.isSynchronizedWithParent();
  22446. };
  22447. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22448. var check = this._cache.mode === this.mode
  22449. && this._cache.minZ === this.minZ
  22450. && this._cache.maxZ === this.maxZ;
  22451. if (!check) {
  22452. return false;
  22453. }
  22454. var engine = this.getEngine();
  22455. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22456. check = this._cache.fov === this.fov
  22457. && this._cache.fovMode === this.fovMode
  22458. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22459. }
  22460. else {
  22461. check = this._cache.orthoLeft === this.orthoLeft
  22462. && this._cache.orthoRight === this.orthoRight
  22463. && this._cache.orthoBottom === this.orthoBottom
  22464. && this._cache.orthoTop === this.orthoTop
  22465. && this._cache.renderWidth === engine.getRenderWidth()
  22466. && this._cache.renderHeight === engine.getRenderHeight();
  22467. }
  22468. return check;
  22469. };
  22470. // Controls
  22471. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22472. };
  22473. Camera.prototype.detachControl = function (element) {
  22474. };
  22475. Camera.prototype.update = function () {
  22476. this._checkInputs();
  22477. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22478. this._updateRigCameras();
  22479. }
  22480. };
  22481. Camera.prototype._checkInputs = function () {
  22482. this.onAfterCheckInputsObservable.notifyObservers(this);
  22483. };
  22484. Object.defineProperty(Camera.prototype, "rigCameras", {
  22485. get: function () {
  22486. return this._rigCameras;
  22487. },
  22488. enumerable: true,
  22489. configurable: true
  22490. });
  22491. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22492. get: function () {
  22493. return this._rigPostProcess;
  22494. },
  22495. enumerable: true,
  22496. configurable: true
  22497. });
  22498. /**
  22499. * Internal, gets the first post proces.
  22500. * @returns the first post process to be run on this camera.
  22501. */
  22502. Camera.prototype._getFirstPostProcess = function () {
  22503. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22504. if (this._postProcesses[ppIndex] !== null) {
  22505. return this._postProcesses[ppIndex];
  22506. }
  22507. }
  22508. return null;
  22509. };
  22510. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22511. // invalidate framebuffer
  22512. var firstPostProcess = this._getFirstPostProcess();
  22513. if (firstPostProcess) {
  22514. firstPostProcess.markTextureDirty();
  22515. }
  22516. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22517. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22518. var cam = this._rigCameras[i];
  22519. var rigPostProcess = cam._rigPostProcess;
  22520. // for VR rig, there does not have to be a post process
  22521. if (rigPostProcess) {
  22522. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22523. if (isPass) {
  22524. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22525. cam.isIntermediate = this._postProcesses.length === 0;
  22526. }
  22527. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22528. rigPostProcess.markTextureDirty();
  22529. }
  22530. else {
  22531. cam._postProcesses = this._postProcesses.slice(0);
  22532. }
  22533. }
  22534. };
  22535. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22536. if (insertAt === void 0) { insertAt = null; }
  22537. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22538. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22539. return 0;
  22540. }
  22541. if (insertAt == null || insertAt < 0) {
  22542. this._postProcesses.push(postProcess);
  22543. }
  22544. else if (this._postProcesses[insertAt] === null) {
  22545. this._postProcesses[insertAt] = postProcess;
  22546. }
  22547. else {
  22548. this._postProcesses.splice(insertAt, 0, postProcess);
  22549. }
  22550. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22551. return this._postProcesses.indexOf(postProcess);
  22552. };
  22553. Camera.prototype.detachPostProcess = function (postProcess) {
  22554. var idx = this._postProcesses.indexOf(postProcess);
  22555. if (idx !== -1) {
  22556. this._postProcesses[idx] = null;
  22557. }
  22558. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22559. };
  22560. Camera.prototype.getWorldMatrix = function () {
  22561. if (this._isSynchronizedViewMatrix()) {
  22562. return this._worldMatrix;
  22563. }
  22564. // Getting the the view matrix will also compute the world matrix.
  22565. this.getViewMatrix();
  22566. return this._worldMatrix;
  22567. };
  22568. Camera.prototype._getViewMatrix = function () {
  22569. return BABYLON.Matrix.Identity();
  22570. };
  22571. Camera.prototype.getViewMatrix = function (force) {
  22572. if (!force && this._isSynchronizedViewMatrix()) {
  22573. return this._computedViewMatrix;
  22574. }
  22575. this.updateCache();
  22576. this._computedViewMatrix = this._getViewMatrix();
  22577. this._currentRenderId = this.getScene().getRenderId();
  22578. this._childRenderId = this._currentRenderId;
  22579. this._refreshFrustumPlanes = true;
  22580. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22581. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22582. }
  22583. this.onViewMatrixChangedObservable.notifyObservers(this);
  22584. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22585. return this._computedViewMatrix;
  22586. };
  22587. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22588. this._doNotComputeProjectionMatrix = true;
  22589. if (projection !== undefined) {
  22590. this._projectionMatrix = projection;
  22591. }
  22592. };
  22593. ;
  22594. Camera.prototype.unfreezeProjectionMatrix = function () {
  22595. this._doNotComputeProjectionMatrix = false;
  22596. };
  22597. ;
  22598. Camera.prototype.getProjectionMatrix = function (force) {
  22599. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22600. return this._projectionMatrix;
  22601. }
  22602. // Cache
  22603. this._cache.mode = this.mode;
  22604. this._cache.minZ = this.minZ;
  22605. this._cache.maxZ = this.maxZ;
  22606. // Matrix
  22607. this._refreshFrustumPlanes = true;
  22608. var engine = this.getEngine();
  22609. var scene = this.getScene();
  22610. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22611. this._cache.fov = this.fov;
  22612. this._cache.fovMode = this.fovMode;
  22613. this._cache.aspectRatio = engine.getAspectRatio(this);
  22614. if (this.minZ <= 0) {
  22615. this.minZ = 0.1;
  22616. }
  22617. if (scene.useRightHandedSystem) {
  22618. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22619. }
  22620. else {
  22621. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22622. }
  22623. }
  22624. else {
  22625. var halfWidth = engine.getRenderWidth() / 2.0;
  22626. var halfHeight = engine.getRenderHeight() / 2.0;
  22627. if (scene.useRightHandedSystem) {
  22628. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22629. }
  22630. else {
  22631. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22632. }
  22633. this._cache.orthoLeft = this.orthoLeft;
  22634. this._cache.orthoRight = this.orthoRight;
  22635. this._cache.orthoBottom = this.orthoBottom;
  22636. this._cache.orthoTop = this.orthoTop;
  22637. this._cache.renderWidth = engine.getRenderWidth();
  22638. this._cache.renderHeight = engine.getRenderHeight();
  22639. }
  22640. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22641. return this._projectionMatrix;
  22642. };
  22643. Camera.prototype.getTranformationMatrix = function () {
  22644. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22645. return this._transformMatrix;
  22646. };
  22647. Camera.prototype.updateFrustumPlanes = function () {
  22648. if (!this._refreshFrustumPlanes) {
  22649. return;
  22650. }
  22651. this.getTranformationMatrix();
  22652. if (!this._frustumPlanes) {
  22653. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22654. }
  22655. else {
  22656. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22657. }
  22658. this._refreshFrustumPlanes = false;
  22659. };
  22660. Camera.prototype.isInFrustum = function (target) {
  22661. this.updateFrustumPlanes();
  22662. return target.isInFrustum(this._frustumPlanes);
  22663. };
  22664. Camera.prototype.isCompletelyInFrustum = function (target) {
  22665. this.updateFrustumPlanes();
  22666. return target.isCompletelyInFrustum(this._frustumPlanes);
  22667. };
  22668. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22669. if (length === void 0) { length = 100; }
  22670. if (!transform) {
  22671. transform = this.getWorldMatrix();
  22672. }
  22673. if (!origin) {
  22674. origin = this.position;
  22675. }
  22676. var forward = new BABYLON.Vector3(0, 0, 1);
  22677. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22678. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22679. return new BABYLON.Ray(origin, direction, length);
  22680. };
  22681. /**
  22682. * Releases resources associated with this node.
  22683. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22684. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22685. */
  22686. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22687. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22688. // Observables
  22689. this.onViewMatrixChangedObservable.clear();
  22690. this.onProjectionMatrixChangedObservable.clear();
  22691. this.onAfterCheckInputsObservable.clear();
  22692. this.onRestoreStateObservable.clear();
  22693. // Inputs
  22694. if (this.inputs) {
  22695. this.inputs.clear();
  22696. }
  22697. // Animations
  22698. this.getScene().stopAnimation(this);
  22699. // Remove from scene
  22700. this.getScene().removeCamera(this);
  22701. while (this._rigCameras.length > 0) {
  22702. var camera = this._rigCameras.pop();
  22703. if (camera) {
  22704. camera.dispose();
  22705. }
  22706. }
  22707. // Postprocesses
  22708. if (this._rigPostProcess) {
  22709. this._rigPostProcess.dispose(this);
  22710. this._rigPostProcess = null;
  22711. this._postProcesses = [];
  22712. }
  22713. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22714. this._rigPostProcess = null;
  22715. this._postProcesses = [];
  22716. }
  22717. else {
  22718. var i = this._postProcesses.length;
  22719. while (--i >= 0) {
  22720. var postProcess = this._postProcesses[i];
  22721. if (postProcess) {
  22722. postProcess.dispose(this);
  22723. }
  22724. }
  22725. }
  22726. // Render targets
  22727. var i = this.customRenderTargets.length;
  22728. while (--i >= 0) {
  22729. this.customRenderTargets[i].dispose();
  22730. }
  22731. this.customRenderTargets = [];
  22732. // Active Meshes
  22733. this._activeMeshes.dispose();
  22734. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22735. };
  22736. Object.defineProperty(Camera.prototype, "leftCamera", {
  22737. // ---- Camera rigs section ----
  22738. get: function () {
  22739. if (this._rigCameras.length < 1) {
  22740. return null;
  22741. }
  22742. return this._rigCameras[0];
  22743. },
  22744. enumerable: true,
  22745. configurable: true
  22746. });
  22747. Object.defineProperty(Camera.prototype, "rightCamera", {
  22748. get: function () {
  22749. if (this._rigCameras.length < 2) {
  22750. return null;
  22751. }
  22752. return this._rigCameras[1];
  22753. },
  22754. enumerable: true,
  22755. configurable: true
  22756. });
  22757. Camera.prototype.getLeftTarget = function () {
  22758. if (this._rigCameras.length < 1) {
  22759. return null;
  22760. }
  22761. return this._rigCameras[0].getTarget();
  22762. };
  22763. Camera.prototype.getRightTarget = function () {
  22764. if (this._rigCameras.length < 2) {
  22765. return null;
  22766. }
  22767. return this._rigCameras[1].getTarget();
  22768. };
  22769. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22770. if (this.cameraRigMode === mode) {
  22771. return;
  22772. }
  22773. while (this._rigCameras.length > 0) {
  22774. var camera = this._rigCameras.pop();
  22775. if (camera) {
  22776. camera.dispose();
  22777. }
  22778. }
  22779. this.cameraRigMode = mode;
  22780. this._cameraRigParams = {};
  22781. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22782. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22783. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22784. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22785. // create the rig cameras, unless none
  22786. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22787. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22788. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22789. if (leftCamera && rightCamera) {
  22790. this._rigCameras.push(leftCamera);
  22791. this._rigCameras.push(rightCamera);
  22792. }
  22793. }
  22794. switch (this.cameraRigMode) {
  22795. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22796. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22797. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22798. break;
  22799. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22800. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22801. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22802. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22803. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22804. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22805. break;
  22806. case Camera.RIG_MODE_VR:
  22807. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22808. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22809. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22810. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22811. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22812. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22813. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22814. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22815. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22816. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22817. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22818. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22819. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22820. if (metrics.compensateDistortion) {
  22821. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22822. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22823. }
  22824. break;
  22825. case Camera.RIG_MODE_WEBVR:
  22826. if (rigParams.vrDisplay) {
  22827. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22828. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22829. //Left eye
  22830. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22831. this._rigCameras[0].setCameraRigParameter("left", true);
  22832. //leaving this for future reference
  22833. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22834. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22835. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22836. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22837. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22838. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22839. this._rigCameras[0].parent = this;
  22840. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22841. //Right eye
  22842. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22843. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22844. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22845. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22846. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22847. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22848. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22849. this._rigCameras[1].parent = this;
  22850. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22851. if (Camera.UseAlternateWebVRRendering) {
  22852. this._rigCameras[1]._skipRendering = true;
  22853. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22854. }
  22855. }
  22856. break;
  22857. }
  22858. this._cascadePostProcessesToRigCams();
  22859. this.update();
  22860. };
  22861. Camera.prototype._getVRProjectionMatrix = function () {
  22862. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22863. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22864. return this._projectionMatrix;
  22865. };
  22866. Camera.prototype._updateCameraRotationMatrix = function () {
  22867. //Here for WebVR
  22868. };
  22869. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22870. //Here for WebVR
  22871. };
  22872. /**
  22873. * This function MUST be overwritten by the different WebVR cameras available.
  22874. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22875. */
  22876. Camera.prototype._getWebVRProjectionMatrix = function () {
  22877. return BABYLON.Matrix.Identity();
  22878. };
  22879. /**
  22880. * This function MUST be overwritten by the different WebVR cameras available.
  22881. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22882. */
  22883. Camera.prototype._getWebVRViewMatrix = function () {
  22884. return BABYLON.Matrix.Identity();
  22885. };
  22886. Camera.prototype.setCameraRigParameter = function (name, value) {
  22887. if (!this._cameraRigParams) {
  22888. this._cameraRigParams = {};
  22889. }
  22890. this._cameraRigParams[name] = value;
  22891. //provisionnally:
  22892. if (name === "interaxialDistance") {
  22893. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22894. }
  22895. };
  22896. /**
  22897. * needs to be overridden by children so sub has required properties to be copied
  22898. */
  22899. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22900. return null;
  22901. };
  22902. /**
  22903. * May need to be overridden by children
  22904. */
  22905. Camera.prototype._updateRigCameras = function () {
  22906. for (var i = 0; i < this._rigCameras.length; i++) {
  22907. this._rigCameras[i].minZ = this.minZ;
  22908. this._rigCameras[i].maxZ = this.maxZ;
  22909. this._rigCameras[i].fov = this.fov;
  22910. }
  22911. // only update viewport when ANAGLYPH
  22912. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22913. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22914. }
  22915. };
  22916. Camera.prototype._setupInputs = function () {
  22917. };
  22918. Camera.prototype.serialize = function () {
  22919. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22920. // Type
  22921. serializationObject.type = this.getClassName();
  22922. // Parent
  22923. if (this.parent) {
  22924. serializationObject.parentId = this.parent.id;
  22925. }
  22926. if (this.inputs) {
  22927. this.inputs.serialize(serializationObject);
  22928. }
  22929. // Animations
  22930. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22931. serializationObject.ranges = this.serializeAnimationRanges();
  22932. return serializationObject;
  22933. };
  22934. Camera.prototype.clone = function (name) {
  22935. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22936. };
  22937. Camera.prototype.getDirection = function (localAxis) {
  22938. var result = BABYLON.Vector3.Zero();
  22939. this.getDirectionToRef(localAxis, result);
  22940. return result;
  22941. };
  22942. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22943. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22944. };
  22945. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22946. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22947. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22948. switch (type) {
  22949. case "ArcRotateCamera":
  22950. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22951. case "DeviceOrientationCamera":
  22952. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22953. case "FollowCamera":
  22954. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22955. case "ArcFollowCamera":
  22956. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22957. case "GamepadCamera":
  22958. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22959. case "TouchCamera":
  22960. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22961. case "VirtualJoysticksCamera":
  22962. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22963. case "WebVRFreeCamera":
  22964. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22965. case "WebVRGamepadCamera":
  22966. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22967. case "VRDeviceOrientationFreeCamera":
  22968. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22969. case "VRDeviceOrientationGamepadCamera":
  22970. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22971. case "AnaglyphArcRotateCamera":
  22972. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22973. case "AnaglyphFreeCamera":
  22974. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22975. case "AnaglyphGamepadCamera":
  22976. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22977. case "AnaglyphUniversalCamera":
  22978. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22979. case "StereoscopicArcRotateCamera":
  22980. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22981. case "StereoscopicFreeCamera":
  22982. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22983. case "StereoscopicGamepadCamera":
  22984. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22985. case "StereoscopicUniversalCamera":
  22986. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22987. case "FreeCamera": // Forcing Universal here
  22988. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22989. default: // Universal Camera is the default value
  22990. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22991. }
  22992. };
  22993. Camera.prototype.computeWorldMatrix = function () {
  22994. return this.getWorldMatrix();
  22995. };
  22996. Camera.Parse = function (parsedCamera, scene) {
  22997. var type = parsedCamera.type;
  22998. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22999. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23000. // Parent
  23001. if (parsedCamera.parentId) {
  23002. camera._waitingParentId = parsedCamera.parentId;
  23003. }
  23004. //If camera has an input manager, let it parse inputs settings
  23005. if (camera.inputs) {
  23006. camera.inputs.parse(parsedCamera);
  23007. camera._setupInputs();
  23008. }
  23009. if (camera.setPosition) { // need to force position
  23010. camera.position.copyFromFloats(0, 0, 0);
  23011. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23012. }
  23013. // Target
  23014. if (parsedCamera.target) {
  23015. if (camera.setTarget) {
  23016. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23017. }
  23018. }
  23019. // Apply 3d rig, when found
  23020. if (parsedCamera.cameraRigMode) {
  23021. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23022. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23023. }
  23024. // Animations
  23025. if (parsedCamera.animations) {
  23026. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23027. var parsedAnimation = parsedCamera.animations[animationIndex];
  23028. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23029. }
  23030. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23031. }
  23032. if (parsedCamera.autoAnimate) {
  23033. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23034. }
  23035. return camera;
  23036. };
  23037. // Statics
  23038. Camera._PERSPECTIVE_CAMERA = 0;
  23039. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23040. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23041. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23042. Camera._RIG_MODE_NONE = 0;
  23043. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23044. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23045. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23046. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23047. Camera._RIG_MODE_VR = 20;
  23048. Camera._RIG_MODE_WEBVR = 21;
  23049. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23050. Camera.UseAlternateWebVRRendering = false;
  23051. __decorate([
  23052. BABYLON.serializeAsVector3()
  23053. ], Camera.prototype, "position", void 0);
  23054. __decorate([
  23055. BABYLON.serializeAsVector3()
  23056. ], Camera.prototype, "upVector", void 0);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Camera.prototype, "orthoLeft", void 0);
  23060. __decorate([
  23061. BABYLON.serialize()
  23062. ], Camera.prototype, "orthoRight", void 0);
  23063. __decorate([
  23064. BABYLON.serialize()
  23065. ], Camera.prototype, "orthoBottom", void 0);
  23066. __decorate([
  23067. BABYLON.serialize()
  23068. ], Camera.prototype, "orthoTop", void 0);
  23069. __decorate([
  23070. BABYLON.serialize()
  23071. ], Camera.prototype, "fov", void 0);
  23072. __decorate([
  23073. BABYLON.serialize()
  23074. ], Camera.prototype, "minZ", void 0);
  23075. __decorate([
  23076. BABYLON.serialize()
  23077. ], Camera.prototype, "maxZ", void 0);
  23078. __decorate([
  23079. BABYLON.serialize()
  23080. ], Camera.prototype, "inertia", void 0);
  23081. __decorate([
  23082. BABYLON.serialize()
  23083. ], Camera.prototype, "mode", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "layerMask", void 0);
  23087. __decorate([
  23088. BABYLON.serialize()
  23089. ], Camera.prototype, "fovMode", void 0);
  23090. __decorate([
  23091. BABYLON.serialize()
  23092. ], Camera.prototype, "cameraRigMode", void 0);
  23093. __decorate([
  23094. BABYLON.serialize()
  23095. ], Camera.prototype, "interaxialDistance", void 0);
  23096. __decorate([
  23097. BABYLON.serialize()
  23098. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23099. return Camera;
  23100. }(BABYLON.Node));
  23101. BABYLON.Camera = Camera;
  23102. })(BABYLON || (BABYLON = {}));
  23103. //# sourceMappingURL=babylon.camera.js.map
  23104. var BABYLON;
  23105. (function (BABYLON) {
  23106. var RenderingManager = /** @class */ (function () {
  23107. function RenderingManager(scene) {
  23108. this._renderingGroups = new Array();
  23109. this._autoClearDepthStencil = {};
  23110. this._customOpaqueSortCompareFn = {};
  23111. this._customAlphaTestSortCompareFn = {};
  23112. this._customTransparentSortCompareFn = {};
  23113. this._renderinGroupInfo = null;
  23114. this._scene = scene;
  23115. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23116. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23117. }
  23118. }
  23119. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23120. if (depth === void 0) { depth = true; }
  23121. if (stencil === void 0) { stencil = true; }
  23122. if (this._depthStencilBufferAlreadyCleaned) {
  23123. return;
  23124. }
  23125. this._scene.getEngine().clear(null, false, depth, stencil);
  23126. this._depthStencilBufferAlreadyCleaned = true;
  23127. };
  23128. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23129. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23130. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23131. var info = null;
  23132. if (observable) {
  23133. if (!this._renderinGroupInfo) {
  23134. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23135. }
  23136. info = this._renderinGroupInfo;
  23137. info.scene = this._scene;
  23138. info.camera = this._scene.activeCamera;
  23139. }
  23140. // Dispatch sprites
  23141. if (renderSprites) {
  23142. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23143. var manager = this._scene.spriteManagers[index];
  23144. this.dispatchSprites(manager);
  23145. }
  23146. }
  23147. // Render
  23148. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23149. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23150. var renderingGroup = this._renderingGroups[index];
  23151. if (!renderingGroup && !observable)
  23152. continue;
  23153. var renderingGroupMask = 0;
  23154. // Fire PRECLEAR stage
  23155. if (observable && info) {
  23156. renderingGroupMask = Math.pow(2, index);
  23157. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23158. info.renderingGroupId = index;
  23159. observable.notifyObservers(info, renderingGroupMask);
  23160. }
  23161. // Clear depth/stencil if needed
  23162. if (RenderingManager.AUTOCLEAR) {
  23163. var autoClear = this._autoClearDepthStencil[index];
  23164. if (autoClear && autoClear.autoClear) {
  23165. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23166. }
  23167. }
  23168. if (observable && info) {
  23169. // Fire PREOPAQUE stage
  23170. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23171. observable.notifyObservers(info, renderingGroupMask);
  23172. // Fire PRETRANSPARENT stage
  23173. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23174. observable.notifyObservers(info, renderingGroupMask);
  23175. }
  23176. if (renderingGroup)
  23177. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23178. // Fire POSTTRANSPARENT stage
  23179. if (observable && info) {
  23180. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23181. observable.notifyObservers(info, renderingGroupMask);
  23182. }
  23183. }
  23184. };
  23185. RenderingManager.prototype.reset = function () {
  23186. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23187. var renderingGroup = this._renderingGroups[index];
  23188. if (renderingGroup) {
  23189. renderingGroup.prepare();
  23190. }
  23191. }
  23192. };
  23193. RenderingManager.prototype.dispose = function () {
  23194. this.freeRenderingGroups();
  23195. this._renderingGroups.length = 0;
  23196. };
  23197. /**
  23198. * Clear the info related to rendering groups preventing retention points during dispose.
  23199. */
  23200. RenderingManager.prototype.freeRenderingGroups = function () {
  23201. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23202. var renderingGroup = this._renderingGroups[index];
  23203. if (renderingGroup) {
  23204. renderingGroup.dispose();
  23205. }
  23206. }
  23207. };
  23208. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23209. if (this._renderingGroups[renderingGroupId] === undefined) {
  23210. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23211. }
  23212. };
  23213. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23214. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23215. this._prepareRenderingGroup(renderingGroupId);
  23216. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23217. };
  23218. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23219. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23220. this._prepareRenderingGroup(renderingGroupId);
  23221. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23222. };
  23223. /**
  23224. * @param subMesh The submesh to dispatch
  23225. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23226. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23227. */
  23228. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23229. if (mesh === undefined) {
  23230. mesh = subMesh.getMesh();
  23231. }
  23232. var renderingGroupId = mesh.renderingGroupId || 0;
  23233. this._prepareRenderingGroup(renderingGroupId);
  23234. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23235. };
  23236. /**
  23237. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23238. * This allowed control for front to back rendering or reversly depending of the special needs.
  23239. *
  23240. * @param renderingGroupId The rendering group id corresponding to its index
  23241. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23242. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23243. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23244. */
  23245. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23249. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23250. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23251. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23252. if (this._renderingGroups[renderingGroupId]) {
  23253. var group = this._renderingGroups[renderingGroupId];
  23254. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23255. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23256. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23257. }
  23258. };
  23259. /**
  23260. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23261. *
  23262. * @param renderingGroupId The rendering group id corresponding to its index
  23263. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23264. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23265. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23266. */
  23267. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23268. if (depth === void 0) { depth = true; }
  23269. if (stencil === void 0) { stencil = true; }
  23270. this._autoClearDepthStencil[renderingGroupId] = {
  23271. autoClear: autoClearDepthStencil,
  23272. depth: depth,
  23273. stencil: stencil
  23274. };
  23275. };
  23276. /**
  23277. * The max id used for rendering groups (not included)
  23278. */
  23279. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23280. /**
  23281. * The min id used for rendering groups (included)
  23282. */
  23283. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23284. /**
  23285. * Used to globally prevent autoclearing scenes.
  23286. */
  23287. RenderingManager.AUTOCLEAR = true;
  23288. return RenderingManager;
  23289. }());
  23290. BABYLON.RenderingManager = RenderingManager;
  23291. })(BABYLON || (BABYLON = {}));
  23292. //# sourceMappingURL=babylon.renderingManager.js.map
  23293. var BABYLON;
  23294. (function (BABYLON) {
  23295. var RenderingGroup = /** @class */ (function () {
  23296. /**
  23297. * Creates a new rendering group.
  23298. * @param index The rendering group index
  23299. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23300. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23301. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23302. */
  23303. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23304. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23305. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23306. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23307. this.index = index;
  23308. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23309. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23310. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23311. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23312. this._particleSystems = new BABYLON.SmartArray(256);
  23313. this._spriteManagers = new BABYLON.SmartArray(256);
  23314. this._edgesRenderers = new BABYLON.SmartArray(16);
  23315. this._scene = scene;
  23316. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23317. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23318. this.transparentSortCompareFn = transparentSortCompareFn;
  23319. }
  23320. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23321. /**
  23322. * Set the opaque sort comparison function.
  23323. * If null the sub meshes will be render in the order they were created
  23324. */
  23325. set: function (value) {
  23326. this._opaqueSortCompareFn = value;
  23327. if (value) {
  23328. this._renderOpaque = this.renderOpaqueSorted;
  23329. }
  23330. else {
  23331. this._renderOpaque = RenderingGroup.renderUnsorted;
  23332. }
  23333. },
  23334. enumerable: true,
  23335. configurable: true
  23336. });
  23337. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23338. /**
  23339. * Set the alpha test sort comparison function.
  23340. * If null the sub meshes will be render in the order they were created
  23341. */
  23342. set: function (value) {
  23343. this._alphaTestSortCompareFn = value;
  23344. if (value) {
  23345. this._renderAlphaTest = this.renderAlphaTestSorted;
  23346. }
  23347. else {
  23348. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23349. }
  23350. },
  23351. enumerable: true,
  23352. configurable: true
  23353. });
  23354. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23355. /**
  23356. * Set the transparent sort comparison function.
  23357. * If null the sub meshes will be render in the order they were created
  23358. */
  23359. set: function (value) {
  23360. if (value) {
  23361. this._transparentSortCompareFn = value;
  23362. }
  23363. else {
  23364. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23365. }
  23366. this._renderTransparent = this.renderTransparentSorted;
  23367. },
  23368. enumerable: true,
  23369. configurable: true
  23370. });
  23371. /**
  23372. * Render all the sub meshes contained in the group.
  23373. * @param customRenderFunction Used to override the default render behaviour of the group.
  23374. * @returns true if rendered some submeshes.
  23375. */
  23376. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23377. if (customRenderFunction) {
  23378. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23379. return;
  23380. }
  23381. var engine = this._scene.getEngine();
  23382. // Depth only
  23383. if (this._depthOnlySubMeshes.length !== 0) {
  23384. engine.setColorWrite(false);
  23385. this._renderAlphaTest(this._depthOnlySubMeshes);
  23386. engine.setColorWrite(true);
  23387. }
  23388. // Opaque
  23389. if (this._opaqueSubMeshes.length !== 0) {
  23390. this._renderOpaque(this._opaqueSubMeshes);
  23391. }
  23392. // Alpha test
  23393. if (this._alphaTestSubMeshes.length !== 0) {
  23394. this._renderAlphaTest(this._alphaTestSubMeshes);
  23395. }
  23396. var stencilState = engine.getStencilBuffer();
  23397. engine.setStencilBuffer(false);
  23398. // Sprites
  23399. if (renderSprites) {
  23400. this._renderSprites();
  23401. }
  23402. // Particles
  23403. if (renderParticles) {
  23404. this._renderParticles(activeMeshes);
  23405. }
  23406. if (this.onBeforeTransparentRendering) {
  23407. this.onBeforeTransparentRendering();
  23408. }
  23409. // Transparent
  23410. if (this._transparentSubMeshes.length !== 0) {
  23411. this._renderTransparent(this._transparentSubMeshes);
  23412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23413. }
  23414. // Set back stencil to false in case it changes before the edge renderer.
  23415. engine.setStencilBuffer(false);
  23416. // Edges
  23417. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23418. this._edgesRenderers.data[edgesRendererIndex].render();
  23419. }
  23420. // Restore Stencil state.
  23421. engine.setStencilBuffer(stencilState);
  23422. };
  23423. /**
  23424. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23425. * @param subMeshes The submeshes to render
  23426. */
  23427. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23428. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23429. };
  23430. /**
  23431. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23432. * @param subMeshes The submeshes to render
  23433. */
  23434. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23435. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23436. };
  23437. /**
  23438. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23439. * @param subMeshes The submeshes to render
  23440. */
  23441. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23442. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23443. };
  23444. /**
  23445. * Renders the submeshes in a specified order.
  23446. * @param subMeshes The submeshes to sort before render
  23447. * @param sortCompareFn The comparison function use to sort
  23448. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23449. * @param transparent Specifies to activate blending if true
  23450. */
  23451. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23452. var subIndex = 0;
  23453. var subMesh;
  23454. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23455. for (; subIndex < subMeshes.length; subIndex++) {
  23456. subMesh = subMeshes.data[subIndex];
  23457. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23458. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23459. }
  23460. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23461. if (sortCompareFn) {
  23462. sortedArray.sort(sortCompareFn);
  23463. }
  23464. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23465. subMesh = sortedArray[subIndex];
  23466. if (transparent) {
  23467. var material = subMesh.getMaterial();
  23468. if (material && material.needDepthPrePass) {
  23469. var engine = material.getScene().getEngine();
  23470. engine.setColorWrite(false);
  23471. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23472. subMesh.render(false);
  23473. engine.setColorWrite(true);
  23474. }
  23475. }
  23476. subMesh.render(transparent);
  23477. }
  23478. };
  23479. /**
  23480. * Renders the submeshes in the order they were dispatched (no sort applied).
  23481. * @param subMeshes The submeshes to render
  23482. */
  23483. RenderingGroup.renderUnsorted = function (subMeshes) {
  23484. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23485. var submesh = subMeshes.data[subIndex];
  23486. submesh.render(false);
  23487. }
  23488. };
  23489. /**
  23490. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23491. * are rendered back to front if in the same alpha index.
  23492. *
  23493. * @param a The first submesh
  23494. * @param b The second submesh
  23495. * @returns The result of the comparison
  23496. */
  23497. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23498. // Alpha index first
  23499. if (a._alphaIndex > b._alphaIndex) {
  23500. return 1;
  23501. }
  23502. if (a._alphaIndex < b._alphaIndex) {
  23503. return -1;
  23504. }
  23505. // Then distance to camera
  23506. return RenderingGroup.backToFrontSortCompare(a, b);
  23507. };
  23508. /**
  23509. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23510. * are rendered back to front.
  23511. *
  23512. * @param a The first submesh
  23513. * @param b The second submesh
  23514. * @returns The result of the comparison
  23515. */
  23516. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23517. // Then distance to camera
  23518. if (a._distanceToCamera < b._distanceToCamera) {
  23519. return 1;
  23520. }
  23521. if (a._distanceToCamera > b._distanceToCamera) {
  23522. return -1;
  23523. }
  23524. return 0;
  23525. };
  23526. /**
  23527. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23528. * are rendered front to back (prevent overdraw).
  23529. *
  23530. * @param a The first submesh
  23531. * @param b The second submesh
  23532. * @returns The result of the comparison
  23533. */
  23534. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23535. // Then distance to camera
  23536. if (a._distanceToCamera < b._distanceToCamera) {
  23537. return -1;
  23538. }
  23539. if (a._distanceToCamera > b._distanceToCamera) {
  23540. return 1;
  23541. }
  23542. return 0;
  23543. };
  23544. /**
  23545. * Resets the different lists of submeshes to prepare a new frame.
  23546. */
  23547. RenderingGroup.prototype.prepare = function () {
  23548. this._opaqueSubMeshes.reset();
  23549. this._transparentSubMeshes.reset();
  23550. this._alphaTestSubMeshes.reset();
  23551. this._depthOnlySubMeshes.reset();
  23552. this._particleSystems.reset();
  23553. this._spriteManagers.reset();
  23554. this._edgesRenderers.reset();
  23555. };
  23556. RenderingGroup.prototype.dispose = function () {
  23557. this._opaqueSubMeshes.dispose();
  23558. this._transparentSubMeshes.dispose();
  23559. this._alphaTestSubMeshes.dispose();
  23560. this._depthOnlySubMeshes.dispose();
  23561. this._particleSystems.dispose();
  23562. this._spriteManagers.dispose();
  23563. this._edgesRenderers.dispose();
  23564. };
  23565. /**
  23566. * Inserts the submesh in its correct queue depending on its material.
  23567. * @param subMesh The submesh to dispatch
  23568. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23569. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23570. */
  23571. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23572. // Get mesh and materials if not provided
  23573. if (mesh === undefined) {
  23574. mesh = subMesh.getMesh();
  23575. }
  23576. if (material === undefined) {
  23577. material = subMesh.getMaterial();
  23578. }
  23579. if (material === null || material === undefined) {
  23580. return;
  23581. }
  23582. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23583. this._transparentSubMeshes.push(subMesh);
  23584. }
  23585. else if (material.needAlphaTesting()) { // Alpha test
  23586. if (material.needDepthPrePass) {
  23587. this._depthOnlySubMeshes.push(subMesh);
  23588. }
  23589. this._alphaTestSubMeshes.push(subMesh);
  23590. }
  23591. else {
  23592. if (material.needDepthPrePass) {
  23593. this._depthOnlySubMeshes.push(subMesh);
  23594. }
  23595. this._opaqueSubMeshes.push(subMesh); // Opaque
  23596. }
  23597. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23598. this._edgesRenderers.push(mesh._edgesRenderer);
  23599. }
  23600. };
  23601. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23602. this._spriteManagers.push(spriteManager);
  23603. };
  23604. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23605. this._particleSystems.push(particleSystem);
  23606. };
  23607. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23608. if (this._particleSystems.length === 0) {
  23609. return;
  23610. }
  23611. // Particles
  23612. var activeCamera = this._scene.activeCamera;
  23613. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23614. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23615. var particleSystem = this._particleSystems.data[particleIndex];
  23616. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23617. continue;
  23618. }
  23619. var emitter = particleSystem.emitter;
  23620. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23621. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23622. }
  23623. }
  23624. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23625. };
  23626. RenderingGroup.prototype._renderSprites = function () {
  23627. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23628. return;
  23629. }
  23630. // Sprites
  23631. var activeCamera = this._scene.activeCamera;
  23632. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23633. for (var id = 0; id < this._spriteManagers.length; id++) {
  23634. var spriteManager = this._spriteManagers.data[id];
  23635. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23636. spriteManager.render();
  23637. }
  23638. }
  23639. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23640. };
  23641. return RenderingGroup;
  23642. }());
  23643. BABYLON.RenderingGroup = RenderingGroup;
  23644. })(BABYLON || (BABYLON = {}));
  23645. //# sourceMappingURL=babylon.renderingGroup.js.map
  23646. var BABYLON;
  23647. (function (BABYLON) {
  23648. /** @hidden */
  23649. var ClickInfo = /** @class */ (function () {
  23650. function ClickInfo() {
  23651. this._singleClick = false;
  23652. this._doubleClick = false;
  23653. this._hasSwiped = false;
  23654. this._ignore = false;
  23655. }
  23656. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23657. get: function () {
  23658. return this._singleClick;
  23659. },
  23660. set: function (b) {
  23661. this._singleClick = b;
  23662. },
  23663. enumerable: true,
  23664. configurable: true
  23665. });
  23666. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23667. get: function () {
  23668. return this._doubleClick;
  23669. },
  23670. set: function (b) {
  23671. this._doubleClick = b;
  23672. },
  23673. enumerable: true,
  23674. configurable: true
  23675. });
  23676. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23677. get: function () {
  23678. return this._hasSwiped;
  23679. },
  23680. set: function (b) {
  23681. this._hasSwiped = b;
  23682. },
  23683. enumerable: true,
  23684. configurable: true
  23685. });
  23686. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23687. get: function () {
  23688. return this._ignore;
  23689. },
  23690. set: function (b) {
  23691. this._ignore = b;
  23692. },
  23693. enumerable: true,
  23694. configurable: true
  23695. });
  23696. return ClickInfo;
  23697. }());
  23698. /**
  23699. * This class is used by the onRenderingGroupObservable
  23700. */
  23701. var RenderingGroupInfo = /** @class */ (function () {
  23702. function RenderingGroupInfo() {
  23703. }
  23704. /**
  23705. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23706. * This stage will be fired no matter what
  23707. */
  23708. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23709. /**
  23710. * Called before opaque object are rendered.
  23711. * This stage will be fired only if there's 3D Opaque content to render
  23712. */
  23713. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23714. /**
  23715. * Called after the opaque objects are rendered and before the transparent ones
  23716. * This stage will be fired only if there's 3D transparent content to render
  23717. */
  23718. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23719. /**
  23720. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23721. * This stage will be fired no matter what
  23722. */
  23723. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23724. return RenderingGroupInfo;
  23725. }());
  23726. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23727. /**
  23728. * Represents a scene to be rendered by the engine.
  23729. * @see http://doc.babylonjs.com/features/scene
  23730. */
  23731. var Scene = /** @class */ (function () {
  23732. /**
  23733. * Creates a new Scene
  23734. * @param engine defines the engine to use to render this scene
  23735. */
  23736. function Scene(engine) {
  23737. // Members
  23738. /**
  23739. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23740. */
  23741. this.autoClear = true;
  23742. /**
  23743. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23744. */
  23745. this.autoClearDepthAndStencil = true;
  23746. /**
  23747. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23748. */
  23749. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23750. /**
  23751. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23752. */
  23753. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23754. this._forceWireframe = false;
  23755. this._forcePointsCloud = false;
  23756. /**
  23757. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23758. */
  23759. this.forceShowBoundingBoxes = false;
  23760. /**
  23761. * Gets or sets a boolean indicating if animations are enabled
  23762. */
  23763. this.animationsEnabled = true;
  23764. this._animationPropertiesOverride = null;
  23765. /**
  23766. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23767. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23768. */
  23769. this.useConstantAnimationDeltaTime = false;
  23770. /**
  23771. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23772. * Please note that it requires to run a ray cast through the scene on every frame
  23773. */
  23774. this.constantlyUpdateMeshUnderPointer = false;
  23775. /**
  23776. * Defines the HTML cursor to use when hovering over interactive elements
  23777. */
  23778. this.hoverCursor = "pointer";
  23779. /**
  23780. * Defines the HTML default cursor to use (empty by default)
  23781. */
  23782. this.defaultCursor = "";
  23783. /**
  23784. * This is used to call preventDefault() on pointer down
  23785. * in order to block unwanted artifacts like system double clicks
  23786. */
  23787. this.preventDefaultOnPointerDown = true;
  23788. // Metadata
  23789. /**
  23790. * Gets or sets user defined metadata
  23791. */
  23792. this.metadata = null;
  23793. /**
  23794. * Use this array to add regular expressions used to disable offline support for specific urls
  23795. */
  23796. this.disableOfflineSupportExceptionRules = new Array();
  23797. /**
  23798. * An event triggered when the scene is disposed.
  23799. */
  23800. this.onDisposeObservable = new BABYLON.Observable();
  23801. this._onDisposeObserver = null;
  23802. /**
  23803. * An event triggered before rendering the scene (right after animations and physics)
  23804. */
  23805. this.onBeforeRenderObservable = new BABYLON.Observable();
  23806. this._onBeforeRenderObserver = null;
  23807. /**
  23808. * An event triggered after rendering the scene
  23809. */
  23810. this.onAfterRenderObservable = new BABYLON.Observable();
  23811. this._onAfterRenderObserver = null;
  23812. /**
  23813. * An event triggered before animating the scene
  23814. */
  23815. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered after animations processing
  23818. */
  23819. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered before draw calls are ready to be sent
  23822. */
  23823. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered after draw calls have been sent
  23826. */
  23827. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered when physic simulation is about to be run
  23830. */
  23831. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered when physic simulation has been done
  23834. */
  23835. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered when the scene is ready
  23838. */
  23839. this.onReadyObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered before rendering a camera
  23842. */
  23843. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23844. this._onBeforeCameraRenderObserver = null;
  23845. /**
  23846. * An event triggered after rendering a camera
  23847. */
  23848. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23849. this._onAfterCameraRenderObserver = null;
  23850. /**
  23851. * An event triggered when active meshes evaluation is about to start
  23852. */
  23853. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23854. /**
  23855. * An event triggered when active meshes evaluation is done
  23856. */
  23857. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23858. /**
  23859. * An event triggered when particles rendering is about to start
  23860. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23861. */
  23862. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23863. /**
  23864. * An event triggered when particles rendering is done
  23865. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23866. */
  23867. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23868. /**
  23869. * An event triggered when sprites rendering is about to start
  23870. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23871. */
  23872. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23873. /**
  23874. * An event triggered when sprites rendering is done
  23875. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23876. */
  23877. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23878. /**
  23879. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23880. */
  23881. this.onDataLoadedObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered when a camera is created
  23884. */
  23885. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23886. /**
  23887. * An event triggered when a camera is removed
  23888. */
  23889. this.onCameraRemovedObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when a light is created
  23892. */
  23893. this.onNewLightAddedObservable = new BABYLON.Observable();
  23894. /**
  23895. * An event triggered when a light is removed
  23896. */
  23897. this.onLightRemovedObservable = new BABYLON.Observable();
  23898. /**
  23899. * An event triggered when a geometry is created
  23900. */
  23901. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when a geometry is removed
  23904. */
  23905. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered when a transform node is created
  23908. */
  23909. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when a transform node is removed
  23912. */
  23913. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when a mesh is created
  23916. */
  23917. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when a mesh is removed
  23920. */
  23921. this.onMeshRemovedObservable = new BABYLON.Observable();
  23922. /**
  23923. * An event triggered when render targets are about to be rendered
  23924. * Can happen multiple times per frame.
  23925. */
  23926. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23927. /**
  23928. * An event triggered when render targets were rendered.
  23929. * Can happen multiple times per frame.
  23930. */
  23931. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23932. /**
  23933. * An event triggered before calculating deterministic simulation step
  23934. */
  23935. this.onBeforeStepObservable = new BABYLON.Observable();
  23936. /**
  23937. * An event triggered after calculating deterministic simulation step
  23938. */
  23939. this.onAfterStepObservable = new BABYLON.Observable();
  23940. /**
  23941. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23942. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23943. * 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)
  23944. */
  23945. this.onRenderingGroupObservable = new BABYLON.Observable();
  23946. // Animations
  23947. /**
  23948. * Gets a list of Animations associated with the scene
  23949. */
  23950. this.animations = [];
  23951. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23952. /**
  23953. * 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).
  23954. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23955. */
  23956. this.onPrePointerObservable = new BABYLON.Observable();
  23957. /**
  23958. * Observable event triggered each time an input event is received from the rendering canvas
  23959. */
  23960. this.onPointerObservable = new BABYLON.Observable();
  23961. this._meshPickProceed = false;
  23962. this._currentPickResult = null;
  23963. this._previousPickResult = null;
  23964. this._totalPointersPressed = 0;
  23965. this._doubleClickOccured = false;
  23966. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23967. this.cameraToUseForPointers = null;
  23968. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23969. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23970. this._startingPointerTime = 0;
  23971. this._previousStartingPointerTime = 0;
  23972. this._pointerCaptures = {};
  23973. // Deterministic lockstep
  23974. this._timeAccumulator = 0;
  23975. this._currentStepId = 0;
  23976. this._currentInternalStep = 0;
  23977. // Keyboard
  23978. /**
  23979. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23980. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23981. */
  23982. this.onPreKeyboardObservable = new BABYLON.Observable();
  23983. /**
  23984. * Observable event triggered each time an keyboard event is received from the hosting window
  23985. */
  23986. this.onKeyboardObservable = new BABYLON.Observable();
  23987. // Coordinates system
  23988. this._useRightHandedSystem = false;
  23989. // Fog
  23990. this._fogEnabled = true;
  23991. this._fogMode = Scene.FOGMODE_NONE;
  23992. /**
  23993. * Gets or sets the fog color to use
  23994. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23995. */
  23996. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23997. /**
  23998. * Gets or sets the fog density to use
  23999. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24000. */
  24001. this.fogDensity = 0.1;
  24002. /**
  24003. * Gets or sets the fog start distance to use
  24004. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24005. */
  24006. this.fogStart = 0;
  24007. /**
  24008. * Gets or sets the fog end distance to use
  24009. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24010. */
  24011. this.fogEnd = 1000.0;
  24012. // Lights
  24013. this._shadowsEnabled = true;
  24014. this._lightsEnabled = true;
  24015. /**
  24016. * All of the lights added to this scene
  24017. * @see http://doc.babylonjs.com/babylon101/lights
  24018. */
  24019. this.lights = new Array();
  24020. // Cameras
  24021. /** All of the cameras added to this scene.
  24022. * @see http://doc.babylonjs.com/babylon101/cameras
  24023. */
  24024. this.cameras = new Array();
  24025. /** All of the active cameras added to this scene. */
  24026. this.activeCameras = new Array();
  24027. // Meshes
  24028. /**
  24029. * All of the tranform nodes added to this scene
  24030. * @see http://doc.babylonjs.com/how_to/transformnode
  24031. */
  24032. this.transformNodes = new Array();
  24033. /**
  24034. * All of the (abstract) meshes added to this scene
  24035. */
  24036. this.meshes = new Array();
  24037. /**
  24038. * All of the animation groups added to this scene
  24039. * @see http://doc.babylonjs.com/how_to/group
  24040. */
  24041. this.animationGroups = new Array();
  24042. // Geometries
  24043. this._geometries = new Array();
  24044. /**
  24045. * All of the materials added to this scene
  24046. * @see http://doc.babylonjs.com/babylon101/materials
  24047. */
  24048. this.materials = new Array();
  24049. /**
  24050. * All of the multi-materials added to this scene
  24051. * @see http://doc.babylonjs.com/how_to/multi_materials
  24052. */
  24053. this.multiMaterials = new Array();
  24054. // Textures
  24055. this._texturesEnabled = true;
  24056. /**
  24057. * All of the textures added to this scene
  24058. */
  24059. this.textures = new Array();
  24060. // Particles
  24061. /**
  24062. * Gets or sets a boolean indicating if particles are enabled on this scene
  24063. */
  24064. this.particlesEnabled = true;
  24065. /**
  24066. * All of the particle systems added to this scene
  24067. * @see http://doc.babylonjs.com/babylon101/particles
  24068. */
  24069. this.particleSystems = new Array();
  24070. // Sprites
  24071. /**
  24072. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24073. */
  24074. this.spritesEnabled = true;
  24075. /**
  24076. * All of the sprite managers added to this scene
  24077. * @see http://doc.babylonjs.com/babylon101/sprites
  24078. */
  24079. this.spriteManagers = new Array();
  24080. /**
  24081. * The list of layers (background and foreground) of the scene
  24082. */
  24083. this.layers = new Array();
  24084. /**
  24085. * The list of effect layers (highlights/glow) added to the scene
  24086. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24087. * @see http://doc.babylonjs.com/how_to/glow_layer
  24088. */
  24089. this.effectLayers = new Array();
  24090. // Skeletons
  24091. this._skeletonsEnabled = true;
  24092. /**
  24093. * The list of skeletons added to the scene
  24094. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24095. */
  24096. this.skeletons = new Array();
  24097. // Morph targets
  24098. /**
  24099. * The list of morph target managers added to the scene
  24100. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24101. */
  24102. this.morphTargetManagers = new Array();
  24103. // Lens flares
  24104. /**
  24105. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24106. */
  24107. this.lensFlaresEnabled = true;
  24108. /**
  24109. * The list of lens flare system added to the scene
  24110. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24111. */
  24112. this.lensFlareSystems = new Array();
  24113. // Collisions
  24114. /**
  24115. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24116. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24117. */
  24118. this.collisionsEnabled = true;
  24119. /**
  24120. * Defines the gravity applied to this scene (used only for collisions)
  24121. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24122. */
  24123. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24124. // Postprocesses
  24125. /**
  24126. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24127. */
  24128. this.postProcessesEnabled = true;
  24129. /**
  24130. * The list of postprocesses added to the scene
  24131. */
  24132. this.postProcesses = new Array();
  24133. // Customs render targets
  24134. /**
  24135. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24136. */
  24137. this.renderTargetsEnabled = true;
  24138. /**
  24139. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24140. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24141. */
  24142. this.dumpNextRenderTargets = false;
  24143. /**
  24144. * The list of user defined render targets added to the scene
  24145. */
  24146. this.customRenderTargets = new Array();
  24147. /**
  24148. * Gets the list of meshes imported to the scene through SceneLoader
  24149. */
  24150. this.importedMeshesFiles = new Array();
  24151. // Probes
  24152. /**
  24153. * Gets or sets a boolean indicating if probes are enabled on this scene
  24154. */
  24155. this.probesEnabled = true;
  24156. /**
  24157. * The list of reflection probes added to the scene
  24158. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24159. */
  24160. this.reflectionProbes = new Array();
  24161. /** @hidden */
  24162. this._actionManagers = new Array();
  24163. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24164. // Procedural textures
  24165. /**
  24166. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24167. */
  24168. this.proceduralTexturesEnabled = true;
  24169. /**
  24170. * The list of procedural textures added to the scene
  24171. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24172. */
  24173. this.proceduralTextures = new Array();
  24174. /**
  24175. * The list of sound tracks added to the scene
  24176. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24177. */
  24178. this.soundTracks = new Array();
  24179. this._audioEnabled = true;
  24180. this._headphone = false;
  24181. // Performance counters
  24182. this._totalVertices = new BABYLON.PerfCounter();
  24183. /** @hidden */
  24184. this._activeIndices = new BABYLON.PerfCounter();
  24185. /** @hidden */
  24186. this._activeParticles = new BABYLON.PerfCounter();
  24187. /** @hidden */
  24188. this._activeBones = new BABYLON.PerfCounter();
  24189. this._animationTime = 0;
  24190. /**
  24191. * Gets or sets a general scale for animation speed
  24192. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24193. */
  24194. this.animationTimeScale = 1;
  24195. this._renderId = 0;
  24196. this._executeWhenReadyTimeoutId = -1;
  24197. this._intermediateRendering = false;
  24198. this._viewUpdateFlag = -1;
  24199. this._projectionUpdateFlag = -1;
  24200. this._alternateViewUpdateFlag = -1;
  24201. this._alternateProjectionUpdateFlag = -1;
  24202. /** @hidden */
  24203. this._toBeDisposed = new BABYLON.SmartArray(256);
  24204. this._activeRequests = new Array();
  24205. this._pendingData = new Array();
  24206. this._isDisposed = false;
  24207. /**
  24208. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24209. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24210. */
  24211. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24212. this._activeMeshes = new BABYLON.SmartArray(256);
  24213. this._processedMaterials = new BABYLON.SmartArray(256);
  24214. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24215. /** @hidden */
  24216. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24217. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24218. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24219. /** @hidden */
  24220. this._activeAnimatables = new Array();
  24221. this._transformMatrix = BABYLON.Matrix.Zero();
  24222. this._useAlternateCameraConfiguration = false;
  24223. this._alternateRendering = false;
  24224. /**
  24225. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24226. * This is useful if there are more lights that the maximum simulteanous authorized
  24227. */
  24228. this.requireLightSorting = false;
  24229. this._depthRenderer = {};
  24230. this._activeMeshesFrozen = false;
  24231. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24232. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24233. this._engine.scenes.push(this);
  24234. this._uid = null;
  24235. this._renderingManager = new BABYLON.RenderingManager(this);
  24236. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24237. if (BABYLON.OutlineRenderer) {
  24238. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24239. }
  24240. if (BABYLON.Tools.IsWindowObjectExist()) {
  24241. this.attachControl();
  24242. }
  24243. //simplification queue
  24244. if (BABYLON.SimplificationQueue) {
  24245. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24246. }
  24247. //collision coordinator initialization. For now legacy per default.
  24248. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24249. // Uniform Buffer
  24250. this._createUbo();
  24251. // Default Image processing definition.
  24252. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24253. }
  24254. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24255. /** The fog is deactivated */
  24256. get: function () {
  24257. return Scene._FOGMODE_NONE;
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24263. /** The fog density is following an exponential function */
  24264. get: function () {
  24265. return Scene._FOGMODE_EXP;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24271. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24272. get: function () {
  24273. return Scene._FOGMODE_EXP2;
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24279. /** The fog density is following a linear function. */
  24280. get: function () {
  24281. return Scene._FOGMODE_LINEAR;
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24287. /**
  24288. * Texture used in all pbr material as the reflection texture.
  24289. * As in the majority of the scene they are the same (exception for multi room and so on),
  24290. * this is easier to reference from here than from all the materials.
  24291. */
  24292. get: function () {
  24293. return this._environmentTexture;
  24294. },
  24295. /**
  24296. * Texture used in all pbr material as the reflection texture.
  24297. * As in the majority of the scene they are the same (exception for multi room and so on),
  24298. * this is easier to set here than in all the materials.
  24299. */
  24300. set: function (value) {
  24301. if (this._environmentTexture === value) {
  24302. return;
  24303. }
  24304. this._environmentTexture = value;
  24305. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24306. },
  24307. enumerable: true,
  24308. configurable: true
  24309. });
  24310. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24311. /**
  24312. * Default image processing configuration used either in the rendering
  24313. * Forward main pass or through the imageProcessingPostProcess if present.
  24314. * As in the majority of the scene they are the same (exception for multi camera),
  24315. * this is easier to reference from here than from all the materials and post process.
  24316. *
  24317. * No setter as we it is a shared configuration, you can set the values instead.
  24318. */
  24319. get: function () {
  24320. return this._imageProcessingConfiguration;
  24321. },
  24322. enumerable: true,
  24323. configurable: true
  24324. });
  24325. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24326. get: function () {
  24327. return this._forceWireframe;
  24328. },
  24329. /**
  24330. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24331. */
  24332. set: function (value) {
  24333. if (this._forceWireframe === value) {
  24334. return;
  24335. }
  24336. this._forceWireframe = value;
  24337. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24338. },
  24339. enumerable: true,
  24340. configurable: true
  24341. });
  24342. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24343. get: function () {
  24344. return this._forcePointsCloud;
  24345. },
  24346. /**
  24347. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24348. */
  24349. set: function (value) {
  24350. if (this._forcePointsCloud === value) {
  24351. return;
  24352. }
  24353. this._forcePointsCloud = value;
  24354. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24360. /**
  24361. * Gets or sets the animation properties override
  24362. */
  24363. get: function () {
  24364. return this._animationPropertiesOverride;
  24365. },
  24366. set: function (value) {
  24367. this._animationPropertiesOverride = value;
  24368. },
  24369. enumerable: true,
  24370. configurable: true
  24371. });
  24372. Object.defineProperty(Scene.prototype, "onDispose", {
  24373. /** Sets a function to be executed when this scene is disposed. */
  24374. set: function (callback) {
  24375. if (this._onDisposeObserver) {
  24376. this.onDisposeObservable.remove(this._onDisposeObserver);
  24377. }
  24378. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(Scene.prototype, "beforeRender", {
  24384. /** Sets a function to be executed before rendering this scene */
  24385. set: function (callback) {
  24386. if (this._onBeforeRenderObserver) {
  24387. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24388. }
  24389. if (callback) {
  24390. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24391. }
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Scene.prototype, "afterRender", {
  24397. /** Sets a function to be executed after rendering this scene */
  24398. set: function (callback) {
  24399. if (this._onAfterRenderObserver) {
  24400. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24401. }
  24402. if (callback) {
  24403. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24404. }
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24410. /** Sets a function to be executed before rendering a camera*/
  24411. set: function (callback) {
  24412. if (this._onBeforeCameraRenderObserver) {
  24413. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24414. }
  24415. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24421. /** Sets a function to be executed after rendering a camera*/
  24422. set: function (callback) {
  24423. if (this._onAfterCameraRenderObserver) {
  24424. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24425. }
  24426. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24432. /**
  24433. * Gets the gamepad manager associated with the scene
  24434. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24435. */
  24436. get: function () {
  24437. if (!this._gamepadManager) {
  24438. this._gamepadManager = new BABYLON.GamepadManager(this);
  24439. }
  24440. return this._gamepadManager;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24446. /**
  24447. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24448. */
  24449. get: function () {
  24450. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24456. get: function () {
  24457. return this._useRightHandedSystem;
  24458. },
  24459. /**
  24460. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24461. */
  24462. set: function (value) {
  24463. if (this._useRightHandedSystem === value) {
  24464. return;
  24465. }
  24466. this._useRightHandedSystem = value;
  24467. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. /**
  24473. * Sets the step Id used by deterministic lock step
  24474. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24475. * @param newStepId defines the step Id
  24476. */
  24477. Scene.prototype.setStepId = function (newStepId) {
  24478. this._currentStepId = newStepId;
  24479. };
  24480. ;
  24481. /**
  24482. * Gets the step Id used by deterministic lock step
  24483. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24484. * @returns the step Id
  24485. */
  24486. Scene.prototype.getStepId = function () {
  24487. return this._currentStepId;
  24488. };
  24489. ;
  24490. /**
  24491. * Gets the internal step used by deterministic lock step
  24492. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24493. * @returns the internal step
  24494. */
  24495. Scene.prototype.getInternalStep = function () {
  24496. return this._currentInternalStep;
  24497. };
  24498. ;
  24499. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24500. get: function () {
  24501. return this._fogEnabled;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if fog is enabled on this scene
  24505. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24506. */
  24507. set: function (value) {
  24508. if (this._fogEnabled === value) {
  24509. return;
  24510. }
  24511. this._fogEnabled = value;
  24512. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Scene.prototype, "fogMode", {
  24518. get: function () {
  24519. return this._fogMode;
  24520. },
  24521. /**
  24522. * Gets or sets the fog mode to use
  24523. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24524. */
  24525. set: function (value) {
  24526. if (this._fogMode === value) {
  24527. return;
  24528. }
  24529. this._fogMode = value;
  24530. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24536. get: function () {
  24537. return this._shadowsEnabled;
  24538. },
  24539. /**
  24540. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24541. */
  24542. set: function (value) {
  24543. if (this._shadowsEnabled === value) {
  24544. return;
  24545. }
  24546. this._shadowsEnabled = value;
  24547. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24553. get: function () {
  24554. return this._lightsEnabled;
  24555. },
  24556. /**
  24557. * Gets or sets a boolean indicating if lights are enabled on this scene
  24558. */
  24559. set: function (value) {
  24560. if (this._lightsEnabled === value) {
  24561. return;
  24562. }
  24563. this._lightsEnabled = value;
  24564. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24570. /** The default material used on meshes when no material is affected */
  24571. get: function () {
  24572. if (!this._defaultMaterial) {
  24573. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24574. }
  24575. return this._defaultMaterial;
  24576. },
  24577. /** The default material used on meshes when no material is affected */
  24578. set: function (value) {
  24579. this._defaultMaterial = value;
  24580. },
  24581. enumerable: true,
  24582. configurable: true
  24583. });
  24584. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24585. get: function () {
  24586. return this._texturesEnabled;
  24587. },
  24588. /**
  24589. * Gets or sets a boolean indicating if textures are enabled on this scene
  24590. */
  24591. set: function (value) {
  24592. if (this._texturesEnabled === value) {
  24593. return;
  24594. }
  24595. this._texturesEnabled = value;
  24596. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24602. get: function () {
  24603. return this._skeletonsEnabled;
  24604. },
  24605. /**
  24606. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24607. */
  24608. set: function (value) {
  24609. if (this._skeletonsEnabled === value) {
  24610. return;
  24611. }
  24612. this._skeletonsEnabled = value;
  24613. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24619. /**
  24620. * Gets the postprocess render pipeline manager
  24621. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24622. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24623. */
  24624. get: function () {
  24625. if (!this._postProcessRenderPipelineManager) {
  24626. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24627. }
  24628. return this._postProcessRenderPipelineManager;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24634. /**
  24635. * Gets the main soundtrack associated with the scene
  24636. */
  24637. get: function () {
  24638. if (!this._mainSoundTrack) {
  24639. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24640. }
  24641. return this._mainSoundTrack;
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24647. /** @hidden */
  24648. get: function () {
  24649. return this._alternateRendering;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24655. /**
  24656. * Gets the list of frustum planes (built from the active camera)
  24657. */
  24658. get: function () {
  24659. return this._frustumPlanes;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24665. /**
  24666. * Gets the current geometry buffer associated to the scene.
  24667. */
  24668. get: function () {
  24669. return this._geometryBufferRenderer;
  24670. },
  24671. /**
  24672. * Sets the current geometry buffer for the scene.
  24673. */
  24674. set: function (geometryBufferRenderer) {
  24675. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24676. this._geometryBufferRenderer = geometryBufferRenderer;
  24677. }
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. Object.defineProperty(Scene.prototype, "debugLayer", {
  24683. /**
  24684. * Gets the debug layer (aka Inspector) associated with the scene
  24685. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24686. */
  24687. get: function () {
  24688. if (!this._debugLayer) {
  24689. this._debugLayer = new BABYLON.DebugLayer(this);
  24690. }
  24691. return this._debugLayer;
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24697. /**
  24698. * Gets a boolean indicating if collisions are processed on a web worker
  24699. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24700. */
  24701. get: function () {
  24702. return this._workerCollisions;
  24703. },
  24704. set: function (enabled) {
  24705. if (!BABYLON.CollisionCoordinatorLegacy) {
  24706. return;
  24707. }
  24708. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24709. this._workerCollisions = enabled;
  24710. if (this.collisionCoordinator) {
  24711. this.collisionCoordinator.destroy();
  24712. }
  24713. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24714. this.collisionCoordinator.init(this);
  24715. },
  24716. enumerable: true,
  24717. configurable: true
  24718. });
  24719. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24720. /**
  24721. * Gets the octree used to boost mesh selection (picking)
  24722. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24723. */
  24724. get: function () {
  24725. return this._selectionOctree;
  24726. },
  24727. enumerable: true,
  24728. configurable: true
  24729. });
  24730. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24731. /**
  24732. * Gets the mesh that is currently under the pointer
  24733. */
  24734. get: function () {
  24735. return this._pointerOverMesh;
  24736. },
  24737. enumerable: true,
  24738. configurable: true
  24739. });
  24740. Object.defineProperty(Scene.prototype, "pointerX", {
  24741. /**
  24742. * Gets the current on-screen X position of the pointer
  24743. */
  24744. get: function () {
  24745. return this._pointerX;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. Object.defineProperty(Scene.prototype, "pointerY", {
  24751. /**
  24752. * Gets the current on-screen Y position of the pointer
  24753. */
  24754. get: function () {
  24755. return this._pointerY;
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. /**
  24761. * Gets the cached material (ie. the latest rendered one)
  24762. * @returns the cached material
  24763. */
  24764. Scene.prototype.getCachedMaterial = function () {
  24765. return this._cachedMaterial;
  24766. };
  24767. /**
  24768. * Gets the cached effect (ie. the latest rendered one)
  24769. * @returns the cached effect
  24770. */
  24771. Scene.prototype.getCachedEffect = function () {
  24772. return this._cachedEffect;
  24773. };
  24774. /**
  24775. * Gets the cached visibility state (ie. the latest rendered one)
  24776. * @returns the cached visibility state
  24777. */
  24778. Scene.prototype.getCachedVisibility = function () {
  24779. return this._cachedVisibility;
  24780. };
  24781. /**
  24782. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24783. * @param material defines the current material
  24784. * @param effect defines the current effect
  24785. * @param visibility defines the current visibility state
  24786. * @returns true if one parameter is not cached
  24787. */
  24788. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24789. if (visibility === void 0) { visibility = 1; }
  24790. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24791. };
  24792. /**
  24793. * Gets the bounding box renderer associated with the scene
  24794. * @returns a BoundingBoxRenderer
  24795. */
  24796. Scene.prototype.getBoundingBoxRenderer = function () {
  24797. if (!this._boundingBoxRenderer) {
  24798. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24799. }
  24800. return this._boundingBoxRenderer;
  24801. };
  24802. /**
  24803. * Gets the outline renderer associated with the scene
  24804. * @returns a OutlineRenderer
  24805. */
  24806. Scene.prototype.getOutlineRenderer = function () {
  24807. return this._outlineRenderer;
  24808. };
  24809. /**
  24810. * Gets the engine associated with the scene
  24811. * @returns an Engine
  24812. */
  24813. Scene.prototype.getEngine = function () {
  24814. return this._engine;
  24815. };
  24816. /**
  24817. * Gets the total number of vertices rendered per frame
  24818. * @returns the total number of vertices rendered per frame
  24819. */
  24820. Scene.prototype.getTotalVertices = function () {
  24821. return this._totalVertices.current;
  24822. };
  24823. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24824. /**
  24825. * Gets the performance counter for total vertices
  24826. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24827. */
  24828. get: function () {
  24829. return this._totalVertices;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. /**
  24835. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24836. * @returns the total number of active indices rendered per frame
  24837. */
  24838. Scene.prototype.getActiveIndices = function () {
  24839. return this._activeIndices.current;
  24840. };
  24841. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24842. /**
  24843. * Gets the performance counter for active indices
  24844. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24845. */
  24846. get: function () {
  24847. return this._activeIndices;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. /**
  24853. * Gets the total number of active particles rendered per frame
  24854. * @returns the total number of active particles rendered per frame
  24855. */
  24856. Scene.prototype.getActiveParticles = function () {
  24857. return this._activeParticles.current;
  24858. };
  24859. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24860. /**
  24861. * Gets the performance counter for active particles
  24862. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24863. */
  24864. get: function () {
  24865. return this._activeParticles;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. /**
  24871. * Gets the total number of active bones rendered per frame
  24872. * @returns the total number of active bones rendered per frame
  24873. */
  24874. Scene.prototype.getActiveBones = function () {
  24875. return this._activeBones.current;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24878. /**
  24879. * Gets the performance counter for active bones
  24880. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24881. */
  24882. get: function () {
  24883. return this._activeBones;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. /** @hidden */
  24889. Scene.prototype.getInterFramePerfCounter = function () {
  24890. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24891. return 0;
  24892. };
  24893. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24894. /** @hidden */
  24895. get: function () {
  24896. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24897. return null;
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. /** @hidden */
  24903. Scene.prototype.getLastFrameDuration = function () {
  24904. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24905. return 0;
  24906. };
  24907. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24908. /** @hidden */
  24909. get: function () {
  24910. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24911. return null;
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. /** @hidden */
  24917. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24918. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24919. return 0;
  24920. };
  24921. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24922. /** @hidden */
  24923. get: function () {
  24924. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24925. return null;
  24926. },
  24927. enumerable: true,
  24928. configurable: true
  24929. });
  24930. /**
  24931. * Gets the array of active meshes
  24932. * @returns an array of AbstractMesh
  24933. */
  24934. Scene.prototype.getActiveMeshes = function () {
  24935. return this._activeMeshes;
  24936. };
  24937. /** @hidden */
  24938. Scene.prototype.getRenderTargetsDuration = function () {
  24939. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24940. return 0;
  24941. };
  24942. /** @hidden */
  24943. Scene.prototype.getRenderDuration = function () {
  24944. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24945. return 0;
  24946. };
  24947. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24948. /** @hidden */
  24949. get: function () {
  24950. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24951. return null;
  24952. },
  24953. enumerable: true,
  24954. configurable: true
  24955. });
  24956. /** @hidden */
  24957. Scene.prototype.getParticlesDuration = function () {
  24958. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24959. return 0;
  24960. };
  24961. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24962. /** @hidden */
  24963. get: function () {
  24964. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24965. return null;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. /** @hidden */
  24971. Scene.prototype.getSpritesDuration = function () {
  24972. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24973. return 0;
  24974. };
  24975. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24976. /** @hidden */
  24977. get: function () {
  24978. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24979. return null;
  24980. },
  24981. enumerable: true,
  24982. configurable: true
  24983. });
  24984. /**
  24985. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24986. * @returns a number
  24987. */
  24988. Scene.prototype.getAnimationRatio = function () {
  24989. return this._animationRatio;
  24990. };
  24991. /**
  24992. * Gets an unique Id for the current frame
  24993. * @returns a number
  24994. */
  24995. Scene.prototype.getRenderId = function () {
  24996. return this._renderId;
  24997. };
  24998. /** Call this function if you want to manually increment the render Id*/
  24999. Scene.prototype.incrementRenderId = function () {
  25000. this._renderId++;
  25001. };
  25002. Scene.prototype._updatePointerPosition = function (evt) {
  25003. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25004. if (!canvasRect) {
  25005. return;
  25006. }
  25007. this._pointerX = evt.clientX - canvasRect.left;
  25008. this._pointerY = evt.clientY - canvasRect.top;
  25009. this._unTranslatedPointerX = this._pointerX;
  25010. this._unTranslatedPointerY = this._pointerY;
  25011. };
  25012. Scene.prototype._createUbo = function () {
  25013. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25014. this._sceneUbo.addUniform("viewProjection", 16);
  25015. this._sceneUbo.addUniform("view", 16);
  25016. };
  25017. Scene.prototype._createAlternateUbo = function () {
  25018. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25019. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25020. this._alternateSceneUbo.addUniform("view", 16);
  25021. };
  25022. // Pointers handling
  25023. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25024. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25025. if (result) {
  25026. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25027. }
  25028. return result;
  25029. };
  25030. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25031. if (pointerInfo.pickInfo) {
  25032. if (!pointerInfo.pickInfo.ray) {
  25033. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25034. }
  25035. }
  25036. };
  25037. /**
  25038. * Use this method to simulate a pointer move on a mesh
  25039. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25040. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25041. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25042. * @returns the current scene
  25043. */
  25044. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25045. var evt = new PointerEvent("pointermove", pointerEventInit);
  25046. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25047. return this;
  25048. }
  25049. return this._processPointerMove(pickResult, evt);
  25050. };
  25051. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25052. var canvas = this._engine.getRenderingCanvas();
  25053. if (!canvas) {
  25054. return this;
  25055. }
  25056. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25057. this.setPointerOverSprite(null);
  25058. this.setPointerOverMesh(pickResult.pickedMesh);
  25059. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25060. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25061. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25062. }
  25063. else {
  25064. canvas.style.cursor = this.hoverCursor;
  25065. }
  25066. }
  25067. else {
  25068. canvas.style.cursor = this.defaultCursor;
  25069. }
  25070. }
  25071. else {
  25072. this.setPointerOverMesh(null);
  25073. // Sprites
  25074. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25075. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25076. this.setPointerOverSprite(pickResult.pickedSprite);
  25077. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25078. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25079. }
  25080. else {
  25081. canvas.style.cursor = this.hoverCursor;
  25082. }
  25083. }
  25084. else {
  25085. this.setPointerOverSprite(null);
  25086. // Restore pointer
  25087. canvas.style.cursor = this.defaultCursor;
  25088. }
  25089. }
  25090. if (pickResult) {
  25091. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25092. if (this.onPointerMove) {
  25093. this.onPointerMove(evt, pickResult, type);
  25094. }
  25095. if (this.onPointerObservable.hasObservers()) {
  25096. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25097. this._setRayOnPointerInfo(pi);
  25098. this.onPointerObservable.notifyObservers(pi, type);
  25099. }
  25100. }
  25101. return this;
  25102. };
  25103. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25104. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25105. if (pickResult) {
  25106. pi.ray = pickResult.ray;
  25107. }
  25108. this.onPrePointerObservable.notifyObservers(pi, type);
  25109. if (pi.skipOnPointerObservable) {
  25110. return true;
  25111. }
  25112. else {
  25113. return false;
  25114. }
  25115. };
  25116. /**
  25117. * Use this method to simulate a pointer down on a mesh
  25118. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25119. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25120. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25121. * @returns the current scene
  25122. */
  25123. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25124. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25125. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25126. return this;
  25127. }
  25128. return this._processPointerDown(pickResult, evt);
  25129. };
  25130. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25131. var _this = this;
  25132. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25133. this._pickedDownMesh = pickResult.pickedMesh;
  25134. var actionManager = pickResult.pickedMesh.actionManager;
  25135. if (actionManager) {
  25136. if (actionManager.hasPickTriggers) {
  25137. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25138. switch (evt.button) {
  25139. case 0:
  25140. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25141. break;
  25142. case 1:
  25143. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25144. break;
  25145. case 2:
  25146. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25147. break;
  25148. }
  25149. }
  25150. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25151. window.setTimeout(function () {
  25152. 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);
  25153. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25154. if (_this._totalPointersPressed !== 0 &&
  25155. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25156. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25157. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25158. _this._startingPointerTime = 0;
  25159. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25160. }
  25161. }
  25162. }, Scene.LongPressDelay);
  25163. }
  25164. }
  25165. }
  25166. if (pickResult) {
  25167. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25168. if (this.onPointerDown) {
  25169. this.onPointerDown(evt, pickResult, type);
  25170. }
  25171. if (this.onPointerObservable.hasObservers()) {
  25172. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25173. this._setRayOnPointerInfo(pi);
  25174. this.onPointerObservable.notifyObservers(pi, type);
  25175. }
  25176. }
  25177. return this;
  25178. };
  25179. /**
  25180. * Use this method to simulate a pointer up on a mesh
  25181. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25182. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25183. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25184. * @returns the current scene
  25185. */
  25186. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25187. var evt = new PointerEvent("pointerup", pointerEventInit);
  25188. var clickInfo = new ClickInfo();
  25189. clickInfo.singleClick = true;
  25190. clickInfo.ignore = true;
  25191. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25192. return this;
  25193. }
  25194. return this._processPointerUp(pickResult, evt, clickInfo);
  25195. };
  25196. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25197. if (pickResult && pickResult && pickResult.pickedMesh) {
  25198. this._pickedUpMesh = pickResult.pickedMesh;
  25199. if (this._pickedDownMesh === this._pickedUpMesh) {
  25200. if (this.onPointerPick) {
  25201. this.onPointerPick(evt, pickResult);
  25202. }
  25203. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25204. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25205. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25206. this._setRayOnPointerInfo(pi);
  25207. this.onPointerObservable.notifyObservers(pi, type_1);
  25208. }
  25209. }
  25210. if (pickResult.pickedMesh.actionManager) {
  25211. if (clickInfo.ignore) {
  25212. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25213. }
  25214. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25215. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25216. }
  25217. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25218. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25219. }
  25220. }
  25221. }
  25222. if (this._pickedDownMesh &&
  25223. this._pickedDownMesh.actionManager &&
  25224. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25225. this._pickedDownMesh !== this._pickedUpMesh) {
  25226. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25227. }
  25228. var type = BABYLON.PointerEventTypes.POINTERUP;
  25229. if (this.onPointerObservable.hasObservers()) {
  25230. if (!clickInfo.ignore) {
  25231. if (!clickInfo.hasSwiped) {
  25232. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25233. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25234. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25235. this._setRayOnPointerInfo(pi);
  25236. this.onPointerObservable.notifyObservers(pi, type_2);
  25237. }
  25238. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25239. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25240. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25241. this._setRayOnPointerInfo(pi);
  25242. this.onPointerObservable.notifyObservers(pi, type_3);
  25243. }
  25244. }
  25245. }
  25246. else {
  25247. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25248. this._setRayOnPointerInfo(pi);
  25249. this.onPointerObservable.notifyObservers(pi, type);
  25250. }
  25251. }
  25252. if (this.onPointerUp) {
  25253. this.onPointerUp(evt, pickResult, type);
  25254. }
  25255. return this;
  25256. };
  25257. /**
  25258. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25259. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25260. * @returns true if the pointer was captured
  25261. */
  25262. Scene.prototype.isPointerCaptured = function (pointerId) {
  25263. if (pointerId === void 0) { pointerId = 0; }
  25264. return this._pointerCaptures[pointerId];
  25265. };
  25266. /**
  25267. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25268. * @param attachUp defines if you want to attach events to pointerup
  25269. * @param attachDown defines if you want to attach events to pointerdown
  25270. * @param attachMove defines if you want to attach events to pointermove
  25271. */
  25272. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25273. var _this = this;
  25274. if (attachUp === void 0) { attachUp = true; }
  25275. if (attachDown === void 0) { attachDown = true; }
  25276. if (attachMove === void 0) { attachMove = true; }
  25277. this._initActionManager = function (act, clickInfo) {
  25278. if (!_this._meshPickProceed) {
  25279. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25280. _this._currentPickResult = pickResult;
  25281. if (pickResult) {
  25282. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25283. }
  25284. _this._meshPickProceed = true;
  25285. }
  25286. return act;
  25287. };
  25288. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25289. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25290. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25291. btn !== _this._previousButtonPressed) {
  25292. _this._doubleClickOccured = false;
  25293. clickInfo.singleClick = true;
  25294. clickInfo.ignore = false;
  25295. cb(clickInfo, _this._currentPickResult);
  25296. }
  25297. };
  25298. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25299. var clickInfo = new ClickInfo();
  25300. _this._currentPickResult = null;
  25301. var act = null;
  25302. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25303. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25304. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25305. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25306. act = _this._initActionManager(act, clickInfo);
  25307. if (act)
  25308. checkPicking = act.hasPickTriggers;
  25309. }
  25310. if (checkPicking) {
  25311. var btn = evt.button;
  25312. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25313. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25314. if (!clickInfo.hasSwiped) {
  25315. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25316. if (!checkSingleClickImmediately) {
  25317. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25318. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25319. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25320. act = _this._initActionManager(act, clickInfo);
  25321. if (act)
  25322. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25323. }
  25324. }
  25325. if (checkSingleClickImmediately) {
  25326. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25327. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25328. btn !== _this._previousButtonPressed) {
  25329. clickInfo.singleClick = true;
  25330. cb(clickInfo, _this._currentPickResult);
  25331. }
  25332. }
  25333. // at least one double click is required to be check and exclusive double click is enabled
  25334. else {
  25335. // wait that no double click has been raised during the double click delay
  25336. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25337. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25338. }
  25339. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25340. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25341. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25342. act = _this._initActionManager(act, clickInfo);
  25343. if (act)
  25344. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25345. }
  25346. if (checkDoubleClick) {
  25347. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25348. if (btn === _this._previousButtonPressed &&
  25349. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25350. !_this._doubleClickOccured) {
  25351. // pointer has not moved for 2 clicks, it's a double click
  25352. if (!clickInfo.hasSwiped &&
  25353. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25354. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25355. _this._previousStartingPointerTime = 0;
  25356. _this._doubleClickOccured = true;
  25357. clickInfo.doubleClick = true;
  25358. clickInfo.ignore = false;
  25359. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25360. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25361. }
  25362. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25363. cb(clickInfo, _this._currentPickResult);
  25364. }
  25365. // if the two successive clicks are too far, it's just two simple clicks
  25366. else {
  25367. _this._doubleClickOccured = false;
  25368. _this._previousStartingPointerTime = _this._startingPointerTime;
  25369. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25370. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25371. _this._previousButtonPressed = btn;
  25372. if (Scene.ExclusiveDoubleClickMode) {
  25373. if (_this._previousDelayedSimpleClickTimeout) {
  25374. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25375. }
  25376. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25377. cb(clickInfo, _this._previousPickResult);
  25378. }
  25379. else {
  25380. cb(clickInfo, _this._currentPickResult);
  25381. }
  25382. }
  25383. }
  25384. // just the first click of the double has been raised
  25385. else {
  25386. _this._doubleClickOccured = false;
  25387. _this._previousStartingPointerTime = _this._startingPointerTime;
  25388. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25389. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25390. _this._previousButtonPressed = btn;
  25391. }
  25392. }
  25393. }
  25394. }
  25395. clickInfo.ignore = true;
  25396. cb(clickInfo, _this._currentPickResult);
  25397. };
  25398. this._spritePredicate = function (sprite) {
  25399. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25400. };
  25401. this._onPointerMove = function (evt) {
  25402. _this._updatePointerPosition(evt);
  25403. // PreObservable support
  25404. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25405. return;
  25406. }
  25407. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25408. return;
  25409. }
  25410. if (!_this.pointerMovePredicate) {
  25411. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25412. }
  25413. // Meshes
  25414. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25415. _this._processPointerMove(pickResult, evt);
  25416. };
  25417. this._onPointerDown = function (evt) {
  25418. _this._totalPointersPressed++;
  25419. _this._pickedDownMesh = null;
  25420. _this._meshPickProceed = false;
  25421. _this._updatePointerPosition(evt);
  25422. if (_this.preventDefaultOnPointerDown && canvas) {
  25423. evt.preventDefault();
  25424. canvas.focus();
  25425. }
  25426. // PreObservable support
  25427. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25428. return;
  25429. }
  25430. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25431. return;
  25432. }
  25433. _this._pointerCaptures[evt.pointerId] = true;
  25434. _this._startingPointerPosition.x = _this._pointerX;
  25435. _this._startingPointerPosition.y = _this._pointerY;
  25436. _this._startingPointerTime = Date.now();
  25437. if (!_this.pointerDownPredicate) {
  25438. _this.pointerDownPredicate = function (mesh) {
  25439. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25440. };
  25441. }
  25442. // Meshes
  25443. _this._pickedDownMesh = null;
  25444. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25445. _this._processPointerDown(pickResult, evt);
  25446. // Sprites
  25447. _this._pickedDownSprite = null;
  25448. if (_this.spriteManagers.length > 0) {
  25449. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25450. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25451. if (pickResult.pickedSprite.actionManager) {
  25452. _this._pickedDownSprite = pickResult.pickedSprite;
  25453. switch (evt.button) {
  25454. case 0:
  25455. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25456. break;
  25457. case 1:
  25458. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25459. break;
  25460. case 2:
  25461. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25462. break;
  25463. }
  25464. if (pickResult.pickedSprite.actionManager) {
  25465. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25466. }
  25467. }
  25468. }
  25469. }
  25470. };
  25471. this._onPointerUp = function (evt) {
  25472. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25473. return; // So we need to test it the pointer down was pressed before.
  25474. }
  25475. _this._totalPointersPressed--;
  25476. _this._pickedUpMesh = null;
  25477. _this._meshPickProceed = false;
  25478. _this._updatePointerPosition(evt);
  25479. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25480. // PreObservable support
  25481. if (_this.onPrePointerObservable.hasObservers()) {
  25482. if (!clickInfo.ignore) {
  25483. if (!clickInfo.hasSwiped) {
  25484. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25485. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25486. return;
  25487. }
  25488. }
  25489. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25490. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25491. return;
  25492. }
  25493. }
  25494. }
  25495. }
  25496. else {
  25497. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25498. return;
  25499. }
  25500. }
  25501. }
  25502. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25503. return;
  25504. }
  25505. _this._pointerCaptures[evt.pointerId] = false;
  25506. if (!_this.pointerUpPredicate) {
  25507. _this.pointerUpPredicate = function (mesh) {
  25508. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25509. };
  25510. }
  25511. // Meshes
  25512. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25513. _this._initActionManager(null, clickInfo);
  25514. }
  25515. if (!pickResult) {
  25516. pickResult = _this._currentPickResult;
  25517. }
  25518. _this._processPointerUp(pickResult, evt, clickInfo);
  25519. // Sprites
  25520. if (!clickInfo.ignore) {
  25521. if (_this.spriteManagers.length > 0) {
  25522. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25523. if (spritePickResult) {
  25524. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25525. if (spritePickResult.pickedSprite.actionManager) {
  25526. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25527. if (spritePickResult.pickedSprite.actionManager) {
  25528. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25529. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25530. }
  25531. }
  25532. }
  25533. }
  25534. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25535. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25536. }
  25537. }
  25538. }
  25539. }
  25540. _this._previousPickResult = _this._currentPickResult;
  25541. });
  25542. };
  25543. this._onKeyDown = function (evt) {
  25544. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25545. if (_this.onPreKeyboardObservable.hasObservers()) {
  25546. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25547. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25548. if (pi.skipOnPointerObservable) {
  25549. return;
  25550. }
  25551. }
  25552. if (_this.onKeyboardObservable.hasObservers()) {
  25553. var pi = new BABYLON.KeyboardInfo(type, evt);
  25554. _this.onKeyboardObservable.notifyObservers(pi, type);
  25555. }
  25556. if (_this.actionManager) {
  25557. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25558. }
  25559. };
  25560. this._onKeyUp = function (evt) {
  25561. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25562. if (_this.onPreKeyboardObservable.hasObservers()) {
  25563. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25564. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25565. if (pi.skipOnPointerObservable) {
  25566. return;
  25567. }
  25568. }
  25569. if (_this.onKeyboardObservable.hasObservers()) {
  25570. var pi = new BABYLON.KeyboardInfo(type, evt);
  25571. _this.onKeyboardObservable.notifyObservers(pi, type);
  25572. }
  25573. if (_this.actionManager) {
  25574. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25575. }
  25576. };
  25577. var engine = this.getEngine();
  25578. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25579. if (!canvas) {
  25580. return;
  25581. }
  25582. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25583. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25584. });
  25585. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25586. if (!canvas) {
  25587. return;
  25588. }
  25589. canvas.removeEventListener("keydown", _this._onKeyDown);
  25590. canvas.removeEventListener("keyup", _this._onKeyUp);
  25591. });
  25592. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25593. var canvas = this._engine.getRenderingCanvas();
  25594. if (!canvas) {
  25595. return;
  25596. }
  25597. if (attachMove) {
  25598. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25599. // Wheel
  25600. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25601. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25602. }
  25603. if (attachDown) {
  25604. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25605. }
  25606. if (attachUp) {
  25607. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25608. }
  25609. canvas.tabIndex = 1;
  25610. };
  25611. /** Detaches all event handlers*/
  25612. Scene.prototype.detachControl = function () {
  25613. var engine = this.getEngine();
  25614. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25615. var canvas = engine.getRenderingCanvas();
  25616. if (!canvas) {
  25617. return;
  25618. }
  25619. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25620. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25621. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25622. if (this._onCanvasBlurObserver) {
  25623. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25624. }
  25625. if (this._onCanvasFocusObserver) {
  25626. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25627. }
  25628. // Wheel
  25629. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25630. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25631. // Keyboard
  25632. canvas.removeEventListener("keydown", this._onKeyDown);
  25633. canvas.removeEventListener("keyup", this._onKeyUp);
  25634. // Observables
  25635. this.onKeyboardObservable.clear();
  25636. this.onPreKeyboardObservable.clear();
  25637. this.onPointerObservable.clear();
  25638. this.onPrePointerObservable.clear();
  25639. };
  25640. /**
  25641. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25642. * Delay loaded resources are not taking in account
  25643. * @return true if all required resources are ready
  25644. */
  25645. Scene.prototype.isReady = function () {
  25646. if (this._isDisposed) {
  25647. return false;
  25648. }
  25649. if (this._pendingData.length > 0) {
  25650. return false;
  25651. }
  25652. var index;
  25653. var engine = this.getEngine();
  25654. // Geometries
  25655. for (index = 0; index < this._geometries.length; index++) {
  25656. var geometry = this._geometries[index];
  25657. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25658. return false;
  25659. }
  25660. }
  25661. // Meshes
  25662. for (index = 0; index < this.meshes.length; index++) {
  25663. var mesh = this.meshes[index];
  25664. if (!mesh.isEnabled()) {
  25665. continue;
  25666. }
  25667. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25668. continue;
  25669. }
  25670. if (!mesh.isReady(true)) {
  25671. return false;
  25672. }
  25673. // Effect layers
  25674. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25675. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25676. var layer = _a[_i];
  25677. if (!layer.hasMesh(mesh)) {
  25678. continue;
  25679. }
  25680. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25681. var subMesh = _c[_b];
  25682. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25683. return false;
  25684. }
  25685. }
  25686. }
  25687. }
  25688. // Post-processes
  25689. if (this.activeCameras && this.activeCameras.length > 0) {
  25690. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25691. var camera = _e[_d];
  25692. if (!camera.isReady(true)) {
  25693. return false;
  25694. }
  25695. }
  25696. }
  25697. else if (this.activeCamera) {
  25698. if (!this.activeCamera.isReady(true)) {
  25699. return false;
  25700. }
  25701. }
  25702. // Particles
  25703. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25704. var particleSystem = _g[_f];
  25705. if (!particleSystem.isReady()) {
  25706. return false;
  25707. }
  25708. }
  25709. return true;
  25710. };
  25711. /** Resets all cached information relative to material (including effect and visibility) */
  25712. Scene.prototype.resetCachedMaterial = function () {
  25713. this._cachedMaterial = null;
  25714. this._cachedEffect = null;
  25715. this._cachedVisibility = null;
  25716. };
  25717. /**
  25718. * Registers a function to be called before every frame render
  25719. * @param func defines the function to register
  25720. */
  25721. Scene.prototype.registerBeforeRender = function (func) {
  25722. this.onBeforeRenderObservable.add(func);
  25723. };
  25724. /**
  25725. * Unregisters a function called before every frame render
  25726. * @param func defines the function to unregister
  25727. */
  25728. Scene.prototype.unregisterBeforeRender = function (func) {
  25729. this.onBeforeRenderObservable.removeCallback(func);
  25730. };
  25731. /**
  25732. * Registers a function to be called after every frame render
  25733. * @param func defines the function to register
  25734. */
  25735. Scene.prototype.registerAfterRender = function (func) {
  25736. this.onAfterRenderObservable.add(func);
  25737. };
  25738. /**
  25739. * Unregisters a function called after every frame render
  25740. * @param func defines the function to unregister
  25741. */
  25742. Scene.prototype.unregisterAfterRender = function (func) {
  25743. this.onAfterRenderObservable.removeCallback(func);
  25744. };
  25745. Scene.prototype._executeOnceBeforeRender = function (func) {
  25746. var _this = this;
  25747. var execFunc = function () {
  25748. func();
  25749. setTimeout(function () {
  25750. _this.unregisterBeforeRender(execFunc);
  25751. });
  25752. };
  25753. this.registerBeforeRender(execFunc);
  25754. };
  25755. /**
  25756. * The provided function will run before render once and will be disposed afterwards.
  25757. * A timeout delay can be provided so that the function will be executed in N ms.
  25758. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25759. * @param func The function to be executed.
  25760. * @param timeout optional delay in ms
  25761. */
  25762. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25763. var _this = this;
  25764. if (timeout !== undefined) {
  25765. setTimeout(function () {
  25766. _this._executeOnceBeforeRender(func);
  25767. }, timeout);
  25768. }
  25769. else {
  25770. this._executeOnceBeforeRender(func);
  25771. }
  25772. };
  25773. /** @hidden */
  25774. Scene.prototype._addPendingData = function (data) {
  25775. this._pendingData.push(data);
  25776. };
  25777. /** @hidden */
  25778. Scene.prototype._removePendingData = function (data) {
  25779. var wasLoading = this.isLoading;
  25780. var index = this._pendingData.indexOf(data);
  25781. if (index !== -1) {
  25782. this._pendingData.splice(index, 1);
  25783. }
  25784. if (wasLoading && !this.isLoading) {
  25785. this.onDataLoadedObservable.notifyObservers(this);
  25786. }
  25787. };
  25788. /**
  25789. * Returns the number of items waiting to be loaded
  25790. * @returns the number of items waiting to be loaded
  25791. */
  25792. Scene.prototype.getWaitingItemsCount = function () {
  25793. return this._pendingData.length;
  25794. };
  25795. Object.defineProperty(Scene.prototype, "isLoading", {
  25796. /**
  25797. * Returns a boolean indicating if the scene is still loading data
  25798. */
  25799. get: function () {
  25800. return this._pendingData.length > 0;
  25801. },
  25802. enumerable: true,
  25803. configurable: true
  25804. });
  25805. /**
  25806. * Registers a function to be executed when the scene is ready
  25807. * @param {Function} func - the function to be executed
  25808. */
  25809. Scene.prototype.executeWhenReady = function (func) {
  25810. var _this = this;
  25811. this.onReadyObservable.add(func);
  25812. if (this._executeWhenReadyTimeoutId !== -1) {
  25813. return;
  25814. }
  25815. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25816. _this._checkIsReady();
  25817. }, 150);
  25818. };
  25819. /**
  25820. * Returns a promise that resolves when the scene is ready
  25821. * @returns A promise that resolves when the scene is ready
  25822. */
  25823. Scene.prototype.whenReadyAsync = function () {
  25824. var _this = this;
  25825. return new Promise(function (resolve) {
  25826. _this.executeWhenReady(function () {
  25827. resolve();
  25828. });
  25829. });
  25830. };
  25831. /** @hidden */
  25832. Scene.prototype._checkIsReady = function () {
  25833. var _this = this;
  25834. if (this.isReady()) {
  25835. this.onReadyObservable.notifyObservers(this);
  25836. this.onReadyObservable.clear();
  25837. this._executeWhenReadyTimeoutId = -1;
  25838. return;
  25839. }
  25840. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25841. _this._checkIsReady();
  25842. }, 150);
  25843. };
  25844. // Animations
  25845. /**
  25846. * Will start the animation sequence of a given target
  25847. * @param target defines the target
  25848. * @param from defines from which frame should animation start
  25849. * @param to defines until which frame should animation run.
  25850. * @param weight defines the weight to apply to the animation (1.0 by default)
  25851. * @param loop defines if the animation loops
  25852. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25853. * @param onAnimationEnd defines the function to be executed when the animation ends
  25854. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25855. * @returns the animatable object created for this animation
  25856. */
  25857. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25858. if (weight === void 0) { weight = 1.0; }
  25859. if (speedRatio === void 0) { speedRatio = 1.0; }
  25860. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25861. returnedAnimatable.weight = weight;
  25862. return returnedAnimatable;
  25863. };
  25864. /**
  25865. * Will start the animation sequence of a given target
  25866. * @param target defines the target
  25867. * @param from defines from which frame should animation start
  25868. * @param to defines until which frame should animation run.
  25869. * @param loop defines if the animation loops
  25870. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25871. * @param onAnimationEnd defines the function to be executed when the animation ends
  25872. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25873. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25874. * @returns the animatable object created for this animation
  25875. */
  25876. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25877. if (speedRatio === void 0) { speedRatio = 1.0; }
  25878. if (stopCurrent === void 0) { stopCurrent = true; }
  25879. if (from > to && speedRatio > 0) {
  25880. speedRatio *= -1;
  25881. }
  25882. if (stopCurrent) {
  25883. this.stopAnimation(target);
  25884. }
  25885. if (!animatable) {
  25886. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25887. }
  25888. // Local animations
  25889. if (target.animations) {
  25890. animatable.appendAnimations(target, target.animations);
  25891. }
  25892. // Children animations
  25893. if (target.getAnimatables) {
  25894. var animatables = target.getAnimatables();
  25895. for (var index = 0; index < animatables.length; index++) {
  25896. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25897. }
  25898. }
  25899. animatable.reset();
  25900. return animatable;
  25901. };
  25902. /**
  25903. * Begin a new animation on a given node
  25904. * @param target defines the target where the animation will take place
  25905. * @param animations defines the list of animations to start
  25906. * @param from defines the initial value
  25907. * @param to defines the final value
  25908. * @param loop defines if you want animation to loop (off by default)
  25909. * @param speedRatio defines the speed ratio to apply to all animations
  25910. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25911. * @returns the list of created animatables
  25912. */
  25913. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25914. if (speedRatio === undefined) {
  25915. speedRatio = 1.0;
  25916. }
  25917. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25918. return animatable;
  25919. };
  25920. /**
  25921. * Begin a new animation on a given node and its hierarchy
  25922. * @param target defines the root node where the animation will take place
  25923. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25924. * @param animations defines the list of animations to start
  25925. * @param from defines the initial value
  25926. * @param to defines the final value
  25927. * @param loop defines if you want animation to loop (off by default)
  25928. * @param speedRatio defines the speed ratio to apply to all animations
  25929. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25930. * @returns the list of animatables created for all nodes
  25931. */
  25932. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25933. var children = target.getDescendants(directDescendantsOnly);
  25934. var result = [];
  25935. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25936. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25937. var child = children_1[_i];
  25938. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25939. }
  25940. return result;
  25941. };
  25942. /**
  25943. * Gets the animatable associated with a specific target
  25944. * @param target defines the target of the animatable
  25945. * @returns the required animatable if found
  25946. */
  25947. Scene.prototype.getAnimatableByTarget = function (target) {
  25948. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25949. if (this._activeAnimatables[index].target === target) {
  25950. return this._activeAnimatables[index];
  25951. }
  25952. }
  25953. return null;
  25954. };
  25955. /**
  25956. * Gets all animatables associated with a given target
  25957. * @param target defines the target to look animatables for
  25958. * @returns an array of Animatables
  25959. */
  25960. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25961. var result = [];
  25962. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25963. if (this._activeAnimatables[index].target === target) {
  25964. result.push(this._activeAnimatables[index]);
  25965. }
  25966. }
  25967. return result;
  25968. };
  25969. Object.defineProperty(Scene.prototype, "animatables", {
  25970. /**
  25971. * Gets all animatable attached to the scene
  25972. */
  25973. get: function () {
  25974. return this._activeAnimatables;
  25975. },
  25976. enumerable: true,
  25977. configurable: true
  25978. });
  25979. /**
  25980. * Will stop the animation of the given target
  25981. * @param target - the target
  25982. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25983. */
  25984. Scene.prototype.stopAnimation = function (target, animationName) {
  25985. var animatables = this.getAllAnimatablesByTarget(target);
  25986. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25987. var animatable = animatables_1[_i];
  25988. animatable.stop(animationName);
  25989. }
  25990. };
  25991. /**
  25992. * Stops and removes all animations that have been applied to the scene
  25993. */
  25994. Scene.prototype.stopAllAnimations = function () {
  25995. if (this._activeAnimatables) {
  25996. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25997. this._activeAnimatables[i].stop();
  25998. }
  25999. this._activeAnimatables = [];
  26000. }
  26001. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26002. var group = _a[_i];
  26003. group.stop();
  26004. }
  26005. };
  26006. Scene.prototype._animate = function () {
  26007. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26008. return;
  26009. }
  26010. // Getting time
  26011. var now = BABYLON.Tools.Now;
  26012. if (!this._animationTimeLast) {
  26013. if (this._pendingData.length > 0) {
  26014. return;
  26015. }
  26016. this._animationTimeLast = now;
  26017. }
  26018. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26019. this._animationTime += deltaTime;
  26020. this._animationTimeLast = now;
  26021. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26022. this._activeAnimatables[index]._animate(this._animationTime);
  26023. }
  26024. // Late animation bindings
  26025. this._processLateAnimationBindings();
  26026. };
  26027. /** @hidden */
  26028. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26029. var target = runtimeAnimation.target;
  26030. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26031. if (!target._lateAnimationHolders) {
  26032. target._lateAnimationHolders = {};
  26033. }
  26034. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26035. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26036. totalWeight: 0,
  26037. animations: [],
  26038. originalValue: originalValue
  26039. };
  26040. }
  26041. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26042. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26043. };
  26044. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26045. var normalizer = 1.0;
  26046. var finalPosition = BABYLON.Tmp.Vector3[0];
  26047. var finalScaling = BABYLON.Tmp.Vector3[1];
  26048. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26049. var startIndex = 0;
  26050. var originalAnimation = holder.animations[0];
  26051. var originalValue = holder.originalValue;
  26052. var scale = 1;
  26053. if (holder.totalWeight < 1.0) {
  26054. // We need to mix the original value in
  26055. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26056. scale = 1.0 - holder.totalWeight;
  26057. }
  26058. else {
  26059. startIndex = 1;
  26060. // We need to normalize the weights
  26061. normalizer = holder.totalWeight;
  26062. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26063. scale = originalAnimation.weight / normalizer;
  26064. if (scale == 1) {
  26065. return originalAnimation.currentValue;
  26066. }
  26067. }
  26068. finalScaling.scaleInPlace(scale);
  26069. finalPosition.scaleInPlace(scale);
  26070. finalQuaternion.scaleInPlace(scale);
  26071. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26072. var runtimeAnimation = holder.animations[animIndex];
  26073. var scale = runtimeAnimation.weight / normalizer;
  26074. var currentPosition = BABYLON.Tmp.Vector3[2];
  26075. var currentScaling = BABYLON.Tmp.Vector3[3];
  26076. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26077. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26078. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26079. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26080. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26081. }
  26082. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26083. return originalAnimation._workValue;
  26084. };
  26085. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26086. var originalAnimation = holder.animations[0];
  26087. var originalValue = holder.originalValue;
  26088. if (holder.animations.length === 1) {
  26089. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26090. }
  26091. var normalizer = 1.0;
  26092. var quaternions;
  26093. var weights;
  26094. if (holder.totalWeight < 1.0) {
  26095. var scale = 1.0 - holder.totalWeight;
  26096. quaternions = [];
  26097. weights = [];
  26098. quaternions.push(originalValue);
  26099. weights.push(scale);
  26100. }
  26101. else {
  26102. if (holder.animations.length === 2) { // Slerp as soon as we can
  26103. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26104. }
  26105. quaternions = [];
  26106. weights = [];
  26107. normalizer = holder.totalWeight;
  26108. }
  26109. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26110. var runtimeAnimation = holder.animations[animIndex];
  26111. quaternions.push(runtimeAnimation.currentValue);
  26112. weights.push(runtimeAnimation.weight / normalizer);
  26113. }
  26114. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26115. var cumulativeAmount = 0;
  26116. var cumulativeQuaternion = null;
  26117. for (var index = 0; index < quaternions.length;) {
  26118. if (!cumulativeQuaternion) {
  26119. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26120. cumulativeAmount = weights[index] + weights[index + 1];
  26121. index += 2;
  26122. continue;
  26123. }
  26124. cumulativeAmount += weights[index];
  26125. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26126. index++;
  26127. }
  26128. return cumulativeQuaternion;
  26129. };
  26130. Scene.prototype._processLateAnimationBindings = function () {
  26131. if (!this._registeredForLateAnimationBindings.length) {
  26132. return;
  26133. }
  26134. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26135. var target = this._registeredForLateAnimationBindings.data[index];
  26136. for (var path in target._lateAnimationHolders) {
  26137. var holder = target._lateAnimationHolders[path];
  26138. var originalAnimation = holder.animations[0];
  26139. var originalValue = holder.originalValue;
  26140. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26141. var finalValue = void 0;
  26142. if (matrixDecomposeMode) {
  26143. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26144. }
  26145. else {
  26146. var quaternionMode = originalValue.w !== undefined;
  26147. if (quaternionMode) {
  26148. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26149. }
  26150. else {
  26151. var startIndex = 0;
  26152. var normalizer = 1.0;
  26153. if (holder.totalWeight < 1.0) {
  26154. // We need to mix the original value in
  26155. if (originalValue.scale) {
  26156. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26157. }
  26158. else {
  26159. finalValue = originalValue * (1.0 - holder.totalWeight);
  26160. }
  26161. }
  26162. else {
  26163. // We need to normalize the weights
  26164. normalizer = holder.totalWeight;
  26165. var scale_1 = originalAnimation.weight / normalizer;
  26166. if (scale_1 !== 1) {
  26167. if (originalAnimation.currentValue.scale) {
  26168. finalValue = originalAnimation.currentValue.scale(scale_1);
  26169. }
  26170. else {
  26171. finalValue = originalAnimation.currentValue * scale_1;
  26172. }
  26173. }
  26174. else {
  26175. finalValue = originalAnimation.currentValue;
  26176. }
  26177. startIndex = 1;
  26178. }
  26179. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26180. var runtimeAnimation = holder.animations[animIndex];
  26181. var scale = runtimeAnimation.weight / normalizer;
  26182. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26183. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26184. }
  26185. else {
  26186. finalValue += runtimeAnimation.currentValue * scale;
  26187. }
  26188. }
  26189. }
  26190. }
  26191. target[path] = finalValue;
  26192. }
  26193. target._lateAnimationHolders = {};
  26194. }
  26195. this._registeredForLateAnimationBindings.reset();
  26196. };
  26197. // Matrix
  26198. /** @hidden */
  26199. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26200. this._useAlternateCameraConfiguration = active;
  26201. };
  26202. /**
  26203. * Gets the current view matrix
  26204. * @returns a Matrix
  26205. */
  26206. Scene.prototype.getViewMatrix = function () {
  26207. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26208. };
  26209. /**
  26210. * Gets the current projection matrix
  26211. * @returns a Matrix
  26212. */
  26213. Scene.prototype.getProjectionMatrix = function () {
  26214. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26215. };
  26216. /**
  26217. * Gets the current transform matrix
  26218. * @returns a Matrix made of View * Projection
  26219. */
  26220. Scene.prototype.getTransformMatrix = function () {
  26221. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26222. };
  26223. /**
  26224. * Sets the current transform matrix
  26225. * @param view defines the View matrix to use
  26226. * @param projection defines the Projection matrix to use
  26227. */
  26228. Scene.prototype.setTransformMatrix = function (view, projection) {
  26229. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26230. return;
  26231. }
  26232. this._viewUpdateFlag = view.updateFlag;
  26233. this._projectionUpdateFlag = projection.updateFlag;
  26234. this._viewMatrix = view;
  26235. this._projectionMatrix = projection;
  26236. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26237. // Update frustum
  26238. if (!this._frustumPlanes) {
  26239. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26240. }
  26241. else {
  26242. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26243. }
  26244. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26245. var otherCamera = this.activeCamera._alternateCamera;
  26246. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26247. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26248. }
  26249. if (this._sceneUbo.useUbo) {
  26250. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26251. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26252. this._sceneUbo.update();
  26253. }
  26254. };
  26255. /** @hidden */
  26256. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26257. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26258. return;
  26259. }
  26260. this._alternateViewUpdateFlag = view.updateFlag;
  26261. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26262. this._alternateViewMatrix = view;
  26263. this._alternateProjectionMatrix = projection;
  26264. if (!this._alternateTransformMatrix) {
  26265. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26266. }
  26267. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26268. if (!this._alternateSceneUbo) {
  26269. this._createAlternateUbo();
  26270. }
  26271. if (this._alternateSceneUbo.useUbo) {
  26272. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26273. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26274. this._alternateSceneUbo.update();
  26275. }
  26276. };
  26277. /**
  26278. * Gets the uniform buffer used to store scene data
  26279. * @returns a UniformBuffer
  26280. */
  26281. Scene.prototype.getSceneUniformBuffer = function () {
  26282. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26283. };
  26284. /**
  26285. * Gets an unique (relatively to the current scene) Id
  26286. * @returns an unique number for the scene
  26287. */
  26288. Scene.prototype.getUniqueId = function () {
  26289. var result = Scene._uniqueIdCounter;
  26290. Scene._uniqueIdCounter++;
  26291. return result;
  26292. };
  26293. /**
  26294. * Add a mesh to the list of scene's meshes
  26295. * @param newMesh defines the mesh to add
  26296. * @param recursive if all child meshes should also be added to the scene
  26297. */
  26298. Scene.prototype.addMesh = function (newMesh, recursive) {
  26299. var _this = this;
  26300. if (recursive === void 0) { recursive = false; }
  26301. this.meshes.push(newMesh);
  26302. //notify the collision coordinator
  26303. if (this.collisionCoordinator) {
  26304. this.collisionCoordinator.onMeshAdded(newMesh);
  26305. }
  26306. newMesh._resyncLightSources();
  26307. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26308. if (recursive) {
  26309. newMesh.getChildMeshes().forEach(function (m) {
  26310. _this.addMesh(m);
  26311. });
  26312. }
  26313. };
  26314. /**
  26315. * Remove a mesh for the list of scene's meshes
  26316. * @param toRemove defines the mesh to remove
  26317. * @param recursive if all child meshes should also be removed from the scene
  26318. * @returns the index where the mesh was in the mesh list
  26319. */
  26320. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26321. var _this = this;
  26322. if (recursive === void 0) { recursive = false; }
  26323. var index = this.meshes.indexOf(toRemove);
  26324. if (index !== -1) {
  26325. // Remove from the scene if mesh found
  26326. this.meshes.splice(index, 1);
  26327. }
  26328. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26329. if (recursive) {
  26330. toRemove.getChildMeshes().forEach(function (m) {
  26331. _this.removeMesh(m);
  26332. });
  26333. }
  26334. return index;
  26335. };
  26336. /**
  26337. * Add a transform node to the list of scene's transform nodes
  26338. * @param newTransformNode defines the transform node to add
  26339. */
  26340. Scene.prototype.addTransformNode = function (newTransformNode) {
  26341. this.transformNodes.push(newTransformNode);
  26342. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26343. };
  26344. /**
  26345. * Remove a transform node for the list of scene's transform nodes
  26346. * @param toRemove defines the transform node to remove
  26347. * @returns the index where the transform node was in the transform node list
  26348. */
  26349. Scene.prototype.removeTransformNode = function (toRemove) {
  26350. var index = this.transformNodes.indexOf(toRemove);
  26351. if (index !== -1) {
  26352. // Remove from the scene if found
  26353. this.transformNodes.splice(index, 1);
  26354. }
  26355. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26356. return index;
  26357. };
  26358. /**
  26359. * Remove a skeleton for the list of scene's skeletons
  26360. * @param toRemove defines the skeleton to remove
  26361. * @returns the index where the skeleton was in the skeleton list
  26362. */
  26363. Scene.prototype.removeSkeleton = function (toRemove) {
  26364. var index = this.skeletons.indexOf(toRemove);
  26365. if (index !== -1) {
  26366. // Remove from the scene if found
  26367. this.skeletons.splice(index, 1);
  26368. }
  26369. return index;
  26370. };
  26371. /**
  26372. * Remove a morph target for the list of scene's morph targets
  26373. * @param toRemove defines the morph target to remove
  26374. * @returns the index where the morph target was in the morph target list
  26375. */
  26376. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26377. var index = this.morphTargetManagers.indexOf(toRemove);
  26378. if (index !== -1) {
  26379. // Remove from the scene if found
  26380. this.morphTargetManagers.splice(index, 1);
  26381. }
  26382. return index;
  26383. };
  26384. /**
  26385. * Remove a light for the list of scene's lights
  26386. * @param toRemove defines the light to remove
  26387. * @returns the index where the light was in the light list
  26388. */
  26389. Scene.prototype.removeLight = function (toRemove) {
  26390. var index = this.lights.indexOf(toRemove);
  26391. if (index !== -1) {
  26392. // Remove from meshes
  26393. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26394. var mesh = _a[_i];
  26395. mesh._removeLightSource(toRemove);
  26396. }
  26397. // Remove from the scene if mesh found
  26398. this.lights.splice(index, 1);
  26399. this.sortLightsByPriority();
  26400. }
  26401. this.onLightRemovedObservable.notifyObservers(toRemove);
  26402. return index;
  26403. };
  26404. /**
  26405. * Remove a camera for the list of scene's cameras
  26406. * @param toRemove defines the camera to remove
  26407. * @returns the index where the camera was in the camera list
  26408. */
  26409. Scene.prototype.removeCamera = function (toRemove) {
  26410. var index = this.cameras.indexOf(toRemove);
  26411. if (index !== -1) {
  26412. // Remove from the scene if mesh found
  26413. this.cameras.splice(index, 1);
  26414. }
  26415. // Remove from activeCameras
  26416. var index2 = this.activeCameras.indexOf(toRemove);
  26417. if (index2 !== -1) {
  26418. // Remove from the scene if mesh found
  26419. this.activeCameras.splice(index2, 1);
  26420. }
  26421. // Reset the activeCamera
  26422. if (this.activeCamera === toRemove) {
  26423. if (this.cameras.length > 0) {
  26424. this.activeCamera = this.cameras[0];
  26425. }
  26426. else {
  26427. this.activeCamera = null;
  26428. }
  26429. }
  26430. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26431. return index;
  26432. };
  26433. /**
  26434. * Remove a particle system for the list of scene's particle systems
  26435. * @param toRemove defines the particle system to remove
  26436. * @returns the index where the particle system was in the particle system list
  26437. */
  26438. Scene.prototype.removeParticleSystem = function (toRemove) {
  26439. var index = this.particleSystems.indexOf(toRemove);
  26440. if (index !== -1) {
  26441. this.particleSystems.splice(index, 1);
  26442. }
  26443. return index;
  26444. };
  26445. /**
  26446. * Remove a animation for the list of scene's animations
  26447. * @param toRemove defines the animation to remove
  26448. * @returns the index where the animation was in the animation list
  26449. */
  26450. Scene.prototype.removeAnimation = function (toRemove) {
  26451. var index = this.animations.indexOf(toRemove);
  26452. if (index !== -1) {
  26453. this.animations.splice(index, 1);
  26454. }
  26455. return index;
  26456. };
  26457. /**
  26458. * Removes the given animation group from this scene.
  26459. * @param toRemove The animation group to remove
  26460. * @returns The index of the removed animation group
  26461. */
  26462. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26463. var index = this.animationGroups.indexOf(toRemove);
  26464. if (index !== -1) {
  26465. this.animationGroups.splice(index, 1);
  26466. }
  26467. return index;
  26468. };
  26469. /**
  26470. * Removes the given multi-material from this scene.
  26471. * @param toRemove The multi-material to remove
  26472. * @returns The index of the removed multi-material
  26473. */
  26474. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26475. var index = this.multiMaterials.indexOf(toRemove);
  26476. if (index !== -1) {
  26477. this.multiMaterials.splice(index, 1);
  26478. }
  26479. return index;
  26480. };
  26481. /**
  26482. * Removes the given material from this scene.
  26483. * @param toRemove The material to remove
  26484. * @returns The index of the removed material
  26485. */
  26486. Scene.prototype.removeMaterial = function (toRemove) {
  26487. var index = this.materials.indexOf(toRemove);
  26488. if (index !== -1) {
  26489. this.materials.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Removes the given lens flare system from this scene.
  26495. * @param toRemove The lens flare system to remove
  26496. * @returns The index of the removed lens flare system
  26497. */
  26498. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26499. var index = this.lensFlareSystems.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. this.lensFlareSystems.splice(index, 1);
  26502. }
  26503. return index;
  26504. };
  26505. /**
  26506. * Removes the given action manager from this scene.
  26507. * @param toRemove The action manager to remove
  26508. * @returns The index of the removed action manager
  26509. */
  26510. Scene.prototype.removeActionManager = function (toRemove) {
  26511. var index = this._actionManagers.indexOf(toRemove);
  26512. if (index !== -1) {
  26513. this._actionManagers.splice(index, 1);
  26514. }
  26515. return index;
  26516. };
  26517. /**
  26518. * Removes the given effect layer from this scene.
  26519. * @param toRemove defines the effect layer to remove
  26520. * @returns the index of the removed effect layer
  26521. */
  26522. Scene.prototype.removeEffectLayer = function (toRemove) {
  26523. var index = this.effectLayers.indexOf(toRemove);
  26524. if (index !== -1) {
  26525. this.effectLayers.splice(index, 1);
  26526. }
  26527. return index;
  26528. };
  26529. /**
  26530. * Removes the given texture from this scene.
  26531. * @param toRemove The texture to remove
  26532. * @returns The index of the removed texture
  26533. */
  26534. Scene.prototype.removeTexture = function (toRemove) {
  26535. var index = this.textures.indexOf(toRemove);
  26536. if (index !== -1) {
  26537. this.textures.splice(index, 1);
  26538. }
  26539. return index;
  26540. };
  26541. /**
  26542. * Adds the given light to this scene
  26543. * @param newLight The light to add
  26544. */
  26545. Scene.prototype.addLight = function (newLight) {
  26546. this.lights.push(newLight);
  26547. this.sortLightsByPriority();
  26548. // Add light to all meshes (To support if the light is removed and then readded)
  26549. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26550. var mesh = _a[_i];
  26551. if (mesh._lightSources.indexOf(newLight) === -1) {
  26552. mesh._lightSources.push(newLight);
  26553. mesh._resyncLightSources();
  26554. }
  26555. }
  26556. this.onNewLightAddedObservable.notifyObservers(newLight);
  26557. };
  26558. /**
  26559. * Sorts the list list based on light priorities
  26560. */
  26561. Scene.prototype.sortLightsByPriority = function () {
  26562. if (this.requireLightSorting) {
  26563. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26564. }
  26565. };
  26566. /**
  26567. * Adds the given camera to this scene
  26568. * @param newCamera The camera to add
  26569. */
  26570. Scene.prototype.addCamera = function (newCamera) {
  26571. this.cameras.push(newCamera);
  26572. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26573. };
  26574. /**
  26575. * Adds the given skeleton to this scene
  26576. * @param newSkeleton The skeleton to add
  26577. */
  26578. Scene.prototype.addSkeleton = function (newSkeleton) {
  26579. this.skeletons.push(newSkeleton);
  26580. };
  26581. /**
  26582. * Adds the given particle system to this scene
  26583. * @param newParticleSystem The particle system to add
  26584. */
  26585. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26586. this.particleSystems.push(newParticleSystem);
  26587. };
  26588. /**
  26589. * Adds the given animation to this scene
  26590. * @param newAnimation The animation to add
  26591. */
  26592. Scene.prototype.addAnimation = function (newAnimation) {
  26593. this.animations.push(newAnimation);
  26594. };
  26595. /**
  26596. * Adds the given animation group to this scene.
  26597. * @param newAnimationGroup The animation group to add
  26598. */
  26599. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26600. this.animationGroups.push(newAnimationGroup);
  26601. };
  26602. /**
  26603. * Adds the given multi-material to this scene
  26604. * @param newMultiMaterial The multi-material to add
  26605. */
  26606. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26607. this.multiMaterials.push(newMultiMaterial);
  26608. };
  26609. /**
  26610. * Adds the given material to this scene
  26611. * @param newMaterial The material to add
  26612. */
  26613. Scene.prototype.addMaterial = function (newMaterial) {
  26614. this.materials.push(newMaterial);
  26615. };
  26616. /**
  26617. * Adds the given morph target to this scene
  26618. * @param newMorphTargetManager The morph target to add
  26619. */
  26620. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26621. this.morphTargetManagers.push(newMorphTargetManager);
  26622. };
  26623. /**
  26624. * Adds the given geometry to this scene
  26625. * @param newGeometry The geometry to add
  26626. */
  26627. Scene.prototype.addGeometry = function (newGeometry) {
  26628. this._geometries.push(newGeometry);
  26629. };
  26630. /**
  26631. * Adds the given lens flare system to this scene
  26632. * @param newLensFlareSystem The lens flare system to add
  26633. */
  26634. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26635. this.lensFlareSystems.push(newLensFlareSystem);
  26636. };
  26637. /**
  26638. * Adds the given effect layer to this scene
  26639. * @param newEffectLayer defines the effect layer to add
  26640. */
  26641. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26642. this.effectLayers.push(newEffectLayer);
  26643. };
  26644. /**
  26645. * Adds the given action manager to this scene
  26646. * @param newActionManager The action manager to add
  26647. */
  26648. Scene.prototype.addActionManager = function (newActionManager) {
  26649. this._actionManagers.push(newActionManager);
  26650. };
  26651. /**
  26652. * Adds the given texture to this scene.
  26653. * @param newTexture The texture to add
  26654. */
  26655. Scene.prototype.addTexture = function (newTexture) {
  26656. this.textures.push(newTexture);
  26657. };
  26658. /**
  26659. * Switch active camera
  26660. * @param newCamera defines the new active camera
  26661. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26662. */
  26663. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26664. if (attachControl === void 0) { attachControl = true; }
  26665. var canvas = this._engine.getRenderingCanvas();
  26666. if (!canvas) {
  26667. return;
  26668. }
  26669. if (this.activeCamera) {
  26670. this.activeCamera.detachControl(canvas);
  26671. }
  26672. this.activeCamera = newCamera;
  26673. if (attachControl) {
  26674. newCamera.attachControl(canvas);
  26675. }
  26676. };
  26677. /**
  26678. * sets the active camera of the scene using its ID
  26679. * @param id defines the camera's ID
  26680. * @return the new active camera or null if none found.
  26681. */
  26682. Scene.prototype.setActiveCameraByID = function (id) {
  26683. var camera = this.getCameraByID(id);
  26684. if (camera) {
  26685. this.activeCamera = camera;
  26686. return camera;
  26687. }
  26688. return null;
  26689. };
  26690. /**
  26691. * sets the active camera of the scene using its name
  26692. * @param name defines the camera's name
  26693. * @returns the new active camera or null if none found.
  26694. */
  26695. Scene.prototype.setActiveCameraByName = function (name) {
  26696. var camera = this.getCameraByName(name);
  26697. if (camera) {
  26698. this.activeCamera = camera;
  26699. return camera;
  26700. }
  26701. return null;
  26702. };
  26703. /**
  26704. * get an animation group using its name
  26705. * @param name defines the material's name
  26706. * @return the animation group or null if none found.
  26707. */
  26708. Scene.prototype.getAnimationGroupByName = function (name) {
  26709. for (var index = 0; index < this.animationGroups.length; index++) {
  26710. if (this.animationGroups[index].name === name) {
  26711. return this.animationGroups[index];
  26712. }
  26713. }
  26714. return null;
  26715. };
  26716. /**
  26717. * get a material using its id
  26718. * @param id defines the material's ID
  26719. * @return the material or null if none found.
  26720. */
  26721. Scene.prototype.getMaterialByID = function (id) {
  26722. for (var index = 0; index < this.materials.length; index++) {
  26723. if (this.materials[index].id === id) {
  26724. return this.materials[index];
  26725. }
  26726. }
  26727. return null;
  26728. };
  26729. /**
  26730. * Gets a material using its name
  26731. * @param name defines the material's name
  26732. * @return the material or null if none found.
  26733. */
  26734. Scene.prototype.getMaterialByName = function (name) {
  26735. for (var index = 0; index < this.materials.length; index++) {
  26736. if (this.materials[index].name === name) {
  26737. return this.materials[index];
  26738. }
  26739. }
  26740. return null;
  26741. };
  26742. /**
  26743. * Gets a lens flare system using its name
  26744. * @param name defines the name to look for
  26745. * @returns the lens flare system or null if not found
  26746. */
  26747. Scene.prototype.getLensFlareSystemByName = function (name) {
  26748. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26749. if (this.lensFlareSystems[index].name === name) {
  26750. return this.lensFlareSystems[index];
  26751. }
  26752. }
  26753. return null;
  26754. };
  26755. /**
  26756. * Gets a lens flare system using its id
  26757. * @param id defines the id to look for
  26758. * @returns the lens flare system or null if not found
  26759. */
  26760. Scene.prototype.getLensFlareSystemByID = function (id) {
  26761. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26762. if (this.lensFlareSystems[index].id === id) {
  26763. return this.lensFlareSystems[index];
  26764. }
  26765. }
  26766. return null;
  26767. };
  26768. /**
  26769. * Gets a camera using its id
  26770. * @param id defines the id to look for
  26771. * @returns the camera or null if not found
  26772. */
  26773. Scene.prototype.getCameraByID = function (id) {
  26774. for (var index = 0; index < this.cameras.length; index++) {
  26775. if (this.cameras[index].id === id) {
  26776. return this.cameras[index];
  26777. }
  26778. }
  26779. return null;
  26780. };
  26781. /**
  26782. * Gets a camera using its unique id
  26783. * @param uniqueId defines the unique id to look for
  26784. * @returns the camera or null if not found
  26785. */
  26786. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26787. for (var index = 0; index < this.cameras.length; index++) {
  26788. if (this.cameras[index].uniqueId === uniqueId) {
  26789. return this.cameras[index];
  26790. }
  26791. }
  26792. return null;
  26793. };
  26794. /**
  26795. * Gets a camera using its name
  26796. * @param name defines the camera's name
  26797. * @return the camera or null if none found.
  26798. */
  26799. Scene.prototype.getCameraByName = function (name) {
  26800. for (var index = 0; index < this.cameras.length; index++) {
  26801. if (this.cameras[index].name === name) {
  26802. return this.cameras[index];
  26803. }
  26804. }
  26805. return null;
  26806. };
  26807. /**
  26808. * Gets a bone using its id
  26809. * @param id defines the bone's id
  26810. * @return the bone or null if not found
  26811. */
  26812. Scene.prototype.getBoneByID = function (id) {
  26813. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26814. var skeleton = this.skeletons[skeletonIndex];
  26815. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26816. if (skeleton.bones[boneIndex].id === id) {
  26817. return skeleton.bones[boneIndex];
  26818. }
  26819. }
  26820. }
  26821. return null;
  26822. };
  26823. /**
  26824. * Gets a bone using its id
  26825. * @param name defines the bone's name
  26826. * @return the bone or null if not found
  26827. */
  26828. Scene.prototype.getBoneByName = function (name) {
  26829. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26830. var skeleton = this.skeletons[skeletonIndex];
  26831. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26832. if (skeleton.bones[boneIndex].name === name) {
  26833. return skeleton.bones[boneIndex];
  26834. }
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * Gets a light node using its name
  26841. * @param name defines the the light's name
  26842. * @return the light or null if none found.
  26843. */
  26844. Scene.prototype.getLightByName = function (name) {
  26845. for (var index = 0; index < this.lights.length; index++) {
  26846. if (this.lights[index].name === name) {
  26847. return this.lights[index];
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Gets a light node using its id
  26854. * @param id defines the light's id
  26855. * @return the light or null if none found.
  26856. */
  26857. Scene.prototype.getLightByID = function (id) {
  26858. for (var index = 0; index < this.lights.length; index++) {
  26859. if (this.lights[index].id === id) {
  26860. return this.lights[index];
  26861. }
  26862. }
  26863. return null;
  26864. };
  26865. /**
  26866. * Gets a light node using its scene-generated unique ID
  26867. * @param uniqueId defines the light's unique id
  26868. * @return the light or null if none found.
  26869. */
  26870. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26871. for (var index = 0; index < this.lights.length; index++) {
  26872. if (this.lights[index].uniqueId === uniqueId) {
  26873. return this.lights[index];
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. /**
  26879. * Gets a particle system by id
  26880. * @param id defines the particle system id
  26881. * @return the corresponding system or null if none found
  26882. */
  26883. Scene.prototype.getParticleSystemByID = function (id) {
  26884. for (var index = 0; index < this.particleSystems.length; index++) {
  26885. if (this.particleSystems[index].id === id) {
  26886. return this.particleSystems[index];
  26887. }
  26888. }
  26889. return null;
  26890. };
  26891. /**
  26892. * Gets a geometry using its ID
  26893. * @param id defines the geometry's id
  26894. * @return the geometry or null if none found.
  26895. */
  26896. Scene.prototype.getGeometryByID = function (id) {
  26897. for (var index = 0; index < this._geometries.length; index++) {
  26898. if (this._geometries[index].id === id) {
  26899. return this._geometries[index];
  26900. }
  26901. }
  26902. return null;
  26903. };
  26904. /**
  26905. * Add a new geometry to this scene
  26906. * @param geometry defines the geometry to be added to the scene.
  26907. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26908. * @return a boolean defining if the geometry was added or not
  26909. */
  26910. Scene.prototype.pushGeometry = function (geometry, force) {
  26911. if (!force && this.getGeometryByID(geometry.id)) {
  26912. return false;
  26913. }
  26914. this._geometries.push(geometry);
  26915. //notify the collision coordinator
  26916. if (this.collisionCoordinator) {
  26917. this.collisionCoordinator.onGeometryAdded(geometry);
  26918. }
  26919. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26920. return true;
  26921. };
  26922. /**
  26923. * Removes an existing geometry
  26924. * @param geometry defines the geometry to be removed from the scene
  26925. * @return a boolean defining if the geometry was removed or not
  26926. */
  26927. Scene.prototype.removeGeometry = function (geometry) {
  26928. var index = this._geometries.indexOf(geometry);
  26929. if (index > -1) {
  26930. this._geometries.splice(index, 1);
  26931. //notify the collision coordinator
  26932. if (this.collisionCoordinator) {
  26933. this.collisionCoordinator.onGeometryDeleted(geometry);
  26934. }
  26935. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26936. return true;
  26937. }
  26938. return false;
  26939. };
  26940. /**
  26941. * Gets the list of geometries attached to the scene
  26942. * @returns an array of Geometry
  26943. */
  26944. Scene.prototype.getGeometries = function () {
  26945. return this._geometries;
  26946. };
  26947. /**
  26948. * Gets the first added mesh found of a given ID
  26949. * @param id defines the id to search for
  26950. * @return the mesh found or null if not found at all
  26951. */
  26952. Scene.prototype.getMeshByID = function (id) {
  26953. for (var index = 0; index < this.meshes.length; index++) {
  26954. if (this.meshes[index].id === id) {
  26955. return this.meshes[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Gets a list of meshes using their id
  26962. * @param id defines the id to search for
  26963. * @returns a list of meshes
  26964. */
  26965. Scene.prototype.getMeshesByID = function (id) {
  26966. return this.meshes.filter(function (m) {
  26967. return m.id === id;
  26968. });
  26969. };
  26970. /**
  26971. * Gets the first added transform node found of a given ID
  26972. * @param id defines the id to search for
  26973. * @return the found transform node or null if not found at all.
  26974. */
  26975. Scene.prototype.getTransformNodeByID = function (id) {
  26976. for (var index = 0; index < this.transformNodes.length; index++) {
  26977. if (this.transformNodes[index].id === id) {
  26978. return this.transformNodes[index];
  26979. }
  26980. }
  26981. return null;
  26982. };
  26983. /**
  26984. * Gets a list of transform nodes using their id
  26985. * @param id defines the id to search for
  26986. * @returns a list of transform nodes
  26987. */
  26988. Scene.prototype.getTransformNodesByID = function (id) {
  26989. return this.transformNodes.filter(function (m) {
  26990. return m.id === id;
  26991. });
  26992. };
  26993. /**
  26994. * Gets a mesh with its auto-generated unique id
  26995. * @param uniqueId defines the unique id to search for
  26996. * @return the found mesh or null if not found at all.
  26997. */
  26998. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26999. for (var index = 0; index < this.meshes.length; index++) {
  27000. if (this.meshes[index].uniqueId === uniqueId) {
  27001. return this.meshes[index];
  27002. }
  27003. }
  27004. return null;
  27005. };
  27006. /**
  27007. * Gets a the last added mesh using a given id
  27008. * @param id defines the id to search for
  27009. * @return the found mesh or null if not found at all.
  27010. */
  27011. Scene.prototype.getLastMeshByID = function (id) {
  27012. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27013. if (this.meshes[index].id === id) {
  27014. return this.meshes[index];
  27015. }
  27016. }
  27017. return null;
  27018. };
  27019. /**
  27020. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27021. * @param id defines the id to search for
  27022. * @return the found node or null if not found at all
  27023. */
  27024. Scene.prototype.getLastEntryByID = function (id) {
  27025. var index;
  27026. for (index = this.meshes.length - 1; index >= 0; index--) {
  27027. if (this.meshes[index].id === id) {
  27028. return this.meshes[index];
  27029. }
  27030. }
  27031. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27032. if (this.transformNodes[index].id === id) {
  27033. return this.transformNodes[index];
  27034. }
  27035. }
  27036. for (index = this.cameras.length - 1; index >= 0; index--) {
  27037. if (this.cameras[index].id === id) {
  27038. return this.cameras[index];
  27039. }
  27040. }
  27041. for (index = this.lights.length - 1; index >= 0; index--) {
  27042. if (this.lights[index].id === id) {
  27043. return this.lights[index];
  27044. }
  27045. }
  27046. return null;
  27047. };
  27048. /**
  27049. * Gets a node (Mesh, Camera, Light) using a given id
  27050. * @param id defines the id to search for
  27051. * @return the found node or null if not found at all
  27052. */
  27053. Scene.prototype.getNodeByID = function (id) {
  27054. var mesh = this.getMeshByID(id);
  27055. if (mesh) {
  27056. return mesh;
  27057. }
  27058. var light = this.getLightByID(id);
  27059. if (light) {
  27060. return light;
  27061. }
  27062. var camera = this.getCameraByID(id);
  27063. if (camera) {
  27064. return camera;
  27065. }
  27066. var bone = this.getBoneByID(id);
  27067. return bone;
  27068. };
  27069. /**
  27070. * Gets a node (Mesh, Camera, Light) using a given name
  27071. * @param name defines the name to search for
  27072. * @return the found node or null if not found at all.
  27073. */
  27074. Scene.prototype.getNodeByName = function (name) {
  27075. var mesh = this.getMeshByName(name);
  27076. if (mesh) {
  27077. return mesh;
  27078. }
  27079. var light = this.getLightByName(name);
  27080. if (light) {
  27081. return light;
  27082. }
  27083. var camera = this.getCameraByName(name);
  27084. if (camera) {
  27085. return camera;
  27086. }
  27087. var bone = this.getBoneByName(name);
  27088. return bone;
  27089. };
  27090. /**
  27091. * Gets a mesh using a given name
  27092. * @param name defines the name to search for
  27093. * @return the found mesh or null if not found at all.
  27094. */
  27095. Scene.prototype.getMeshByName = function (name) {
  27096. for (var index = 0; index < this.meshes.length; index++) {
  27097. if (this.meshes[index].name === name) {
  27098. return this.meshes[index];
  27099. }
  27100. }
  27101. return null;
  27102. };
  27103. /**
  27104. * Gets a transform node using a given name
  27105. * @param name defines the name to search for
  27106. * @return the found transform node or null if not found at all.
  27107. */
  27108. Scene.prototype.getTransformNodeByName = function (name) {
  27109. for (var index = 0; index < this.transformNodes.length; index++) {
  27110. if (this.transformNodes[index].name === name) {
  27111. return this.transformNodes[index];
  27112. }
  27113. }
  27114. return null;
  27115. };
  27116. /**
  27117. * Gets a sound using a given name
  27118. * @param name defines the name to search for
  27119. * @return the found sound or null if not found at all.
  27120. */
  27121. Scene.prototype.getSoundByName = function (name) {
  27122. var index;
  27123. if (BABYLON.AudioEngine) {
  27124. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27125. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27126. return this.mainSoundTrack.soundCollection[index];
  27127. }
  27128. }
  27129. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27130. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27131. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27132. return this.soundTracks[sdIndex].soundCollection[index];
  27133. }
  27134. }
  27135. }
  27136. }
  27137. return null;
  27138. };
  27139. /**
  27140. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27141. * @param id defines the id to search for
  27142. * @return the found skeleton or null if not found at all.
  27143. */
  27144. Scene.prototype.getLastSkeletonByID = function (id) {
  27145. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27146. if (this.skeletons[index].id === id) {
  27147. return this.skeletons[index];
  27148. }
  27149. }
  27150. return null;
  27151. };
  27152. /**
  27153. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27154. * @param id defines the id to search for
  27155. * @return the found skeleton or null if not found at all.
  27156. */
  27157. Scene.prototype.getSkeletonById = function (id) {
  27158. for (var index = 0; index < this.skeletons.length; index++) {
  27159. if (this.skeletons[index].id === id) {
  27160. return this.skeletons[index];
  27161. }
  27162. }
  27163. return null;
  27164. };
  27165. /**
  27166. * Gets a skeleton using a given name
  27167. * @param name defines the name to search for
  27168. * @return the found skeleton or null if not found at all.
  27169. */
  27170. Scene.prototype.getSkeletonByName = function (name) {
  27171. for (var index = 0; index < this.skeletons.length; index++) {
  27172. if (this.skeletons[index].name === name) {
  27173. return this.skeletons[index];
  27174. }
  27175. }
  27176. return null;
  27177. };
  27178. /**
  27179. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27180. * @param id defines the id to search for
  27181. * @return the found morph target manager or null if not found at all.
  27182. */
  27183. Scene.prototype.getMorphTargetManagerById = function (id) {
  27184. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27185. if (this.morphTargetManagers[index].uniqueId === id) {
  27186. return this.morphTargetManagers[index];
  27187. }
  27188. }
  27189. return null;
  27190. };
  27191. /**
  27192. * Gets a boolean indicating if the given mesh is active
  27193. * @param mesh defines the mesh to look for
  27194. * @returns true if the mesh is in the active list
  27195. */
  27196. Scene.prototype.isActiveMesh = function (mesh) {
  27197. return (this._activeMeshes.indexOf(mesh) !== -1);
  27198. };
  27199. /**
  27200. * Return a the first highlight layer of the scene with a given name.
  27201. * @param name The name of the highlight layer to look for.
  27202. * @return The highlight layer if found otherwise null.
  27203. */
  27204. Scene.prototype.getHighlightLayerByName = function (name) {
  27205. for (var index = 0; index < this.effectLayers.length; index++) {
  27206. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27207. return this.effectLayers[index];
  27208. }
  27209. }
  27210. return null;
  27211. };
  27212. /**
  27213. * Return a the first highlight layer of the scene with a given name.
  27214. * @param name The name of the highlight layer to look for.
  27215. * @return The highlight layer if found otherwise null.
  27216. */
  27217. Scene.prototype.getGlowLayerByName = function (name) {
  27218. for (var index = 0; index < this.effectLayers.length; index++) {
  27219. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27220. return this.effectLayers[index];
  27221. }
  27222. }
  27223. return null;
  27224. };
  27225. Object.defineProperty(Scene.prototype, "uid", {
  27226. /**
  27227. * Return a unique id as a string which can serve as an identifier for the scene
  27228. */
  27229. get: function () {
  27230. if (!this._uid) {
  27231. this._uid = BABYLON.Tools.RandomId();
  27232. }
  27233. return this._uid;
  27234. },
  27235. enumerable: true,
  27236. configurable: true
  27237. });
  27238. /**
  27239. * Add an externaly attached data from its key.
  27240. * This method call will fail and return false, if such key already exists.
  27241. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27242. * @param key the unique key that identifies the data
  27243. * @param data the data object to associate to the key for this Engine instance
  27244. * @return true if no such key were already present and the data was added successfully, false otherwise
  27245. */
  27246. Scene.prototype.addExternalData = function (key, data) {
  27247. if (!this._externalData) {
  27248. this._externalData = new BABYLON.StringDictionary();
  27249. }
  27250. return this._externalData.add(key, data);
  27251. };
  27252. /**
  27253. * Get an externaly attached data from its key
  27254. * @param key the unique key that identifies the data
  27255. * @return the associated data, if present (can be null), or undefined if not present
  27256. */
  27257. Scene.prototype.getExternalData = function (key) {
  27258. if (!this._externalData) {
  27259. return null;
  27260. }
  27261. return this._externalData.get(key);
  27262. };
  27263. /**
  27264. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27265. * @param key the unique key that identifies the data
  27266. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27267. * @return the associated data, can be null if the factory returned null.
  27268. */
  27269. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27270. if (!this._externalData) {
  27271. this._externalData = new BABYLON.StringDictionary();
  27272. }
  27273. return this._externalData.getOrAddWithFactory(key, factory);
  27274. };
  27275. /**
  27276. * Remove an externaly attached data from the Engine instance
  27277. * @param key the unique key that identifies the data
  27278. * @return true if the data was successfully removed, false if it doesn't exist
  27279. */
  27280. Scene.prototype.removeExternalData = function (key) {
  27281. return this._externalData.remove(key);
  27282. };
  27283. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27284. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27285. if (mesh.showSubMeshesBoundingBox) {
  27286. var boundingInfo = subMesh.getBoundingInfo();
  27287. if (boundingInfo !== null && boundingInfo !== undefined) {
  27288. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27289. }
  27290. }
  27291. var material = subMesh.getMaterial();
  27292. if (material !== null && material !== undefined) {
  27293. // Render targets
  27294. if (material.getRenderTargetTextures !== undefined) {
  27295. if (this._processedMaterials.indexOf(material) === -1) {
  27296. this._processedMaterials.push(material);
  27297. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27298. }
  27299. }
  27300. // Dispatch
  27301. this._activeIndices.addCount(subMesh.indexCount, false);
  27302. this._renderingManager.dispatch(subMesh, mesh, material);
  27303. }
  27304. }
  27305. };
  27306. /**
  27307. * Clear the processed materials smart array preventing retention point in material dispose.
  27308. */
  27309. Scene.prototype.freeProcessedMaterials = function () {
  27310. this._processedMaterials.dispose();
  27311. };
  27312. /**
  27313. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27314. */
  27315. Scene.prototype.freeActiveMeshes = function () {
  27316. this._activeMeshes.dispose();
  27317. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27318. this.activeCamera._activeMeshes.dispose();
  27319. }
  27320. if (this.activeCameras) {
  27321. for (var i = 0; i < this.activeCameras.length; i++) {
  27322. var activeCamera = this.activeCameras[i];
  27323. if (activeCamera && activeCamera._activeMeshes) {
  27324. activeCamera._activeMeshes.dispose();
  27325. }
  27326. }
  27327. }
  27328. };
  27329. /**
  27330. * Clear the info related to rendering groups preventing retention points during dispose.
  27331. */
  27332. Scene.prototype.freeRenderingGroups = function () {
  27333. if (this._renderingManager) {
  27334. this._renderingManager.freeRenderingGroups();
  27335. }
  27336. if (this.textures) {
  27337. for (var i = 0; i < this.textures.length; i++) {
  27338. var texture = this.textures[i];
  27339. if (texture && texture.renderList) {
  27340. texture.freeRenderingGroups();
  27341. }
  27342. }
  27343. }
  27344. };
  27345. /** @hidden */
  27346. Scene.prototype._isInIntermediateRendering = function () {
  27347. return this._intermediateRendering;
  27348. };
  27349. /**
  27350. * Defines the current active mesh candidate provider
  27351. * @param provider defines the provider to use
  27352. */
  27353. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27354. this._activeMeshCandidateProvider = provider;
  27355. };
  27356. /**
  27357. * Gets the current active mesh candidate provider
  27358. * @returns the current active mesh candidate provider
  27359. */
  27360. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27361. return this._activeMeshCandidateProvider;
  27362. };
  27363. /**
  27364. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27365. * @returns the current scene
  27366. */
  27367. Scene.prototype.freezeActiveMeshes = function () {
  27368. if (!this.activeCamera) {
  27369. return this;
  27370. }
  27371. if (!this._frustumPlanes) {
  27372. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27373. }
  27374. this._evaluateActiveMeshes();
  27375. this._activeMeshesFrozen = true;
  27376. return this;
  27377. };
  27378. /**
  27379. * Use this function to restart evaluating active meshes on every frame
  27380. * @returns the current scene
  27381. */
  27382. Scene.prototype.unfreezeActiveMeshes = function () {
  27383. this._activeMeshesFrozen = false;
  27384. return this;
  27385. };
  27386. Scene.prototype._evaluateActiveMeshes = function () {
  27387. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27388. return;
  27389. }
  27390. if (!this.activeCamera) {
  27391. return;
  27392. }
  27393. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27394. this.activeCamera._activeMeshes.reset();
  27395. this._activeMeshes.reset();
  27396. this._renderingManager.reset();
  27397. this._processedMaterials.reset();
  27398. this._activeParticleSystems.reset();
  27399. this._activeSkeletons.reset();
  27400. this._softwareSkinnedMeshes.reset();
  27401. if (this._boundingBoxRenderer) {
  27402. this._boundingBoxRenderer.reset();
  27403. }
  27404. // Meshes
  27405. var meshes;
  27406. var len;
  27407. var checkIsEnabled = true;
  27408. // Determine mesh candidates
  27409. if (this._activeMeshCandidateProvider !== undefined) {
  27410. // Use _activeMeshCandidateProvider
  27411. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27412. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27413. if (meshes !== undefined) {
  27414. len = meshes.length;
  27415. }
  27416. else {
  27417. len = 0;
  27418. }
  27419. }
  27420. else if (this._selectionOctree !== undefined) {
  27421. // Octree
  27422. var selection = this._selectionOctree.select(this._frustumPlanes);
  27423. meshes = selection.data;
  27424. len = selection.length;
  27425. }
  27426. else {
  27427. // Full scene traversal
  27428. len = this.meshes.length;
  27429. meshes = this.meshes;
  27430. }
  27431. // Check each mesh
  27432. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27433. mesh = meshes[meshIndex];
  27434. if (mesh.isBlocked) {
  27435. continue;
  27436. }
  27437. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27438. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27439. continue;
  27440. }
  27441. mesh.computeWorldMatrix();
  27442. // Intersections
  27443. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27444. this._meshesForIntersections.pushNoDuplicate(mesh);
  27445. }
  27446. // Switch to current LOD
  27447. meshLOD = mesh.getLOD(this.activeCamera);
  27448. if (meshLOD === undefined || meshLOD === null) {
  27449. continue;
  27450. }
  27451. mesh._preActivate();
  27452. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27453. this._activeMeshes.push(mesh);
  27454. this.activeCamera._activeMeshes.push(mesh);
  27455. mesh._activate(this._renderId);
  27456. if (meshLOD !== mesh) {
  27457. meshLOD._activate(this._renderId);
  27458. }
  27459. this._activeMesh(mesh, meshLOD);
  27460. }
  27461. }
  27462. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27463. // Particle systems
  27464. if (this.particlesEnabled) {
  27465. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27466. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27467. var particleSystem = this.particleSystems[particleIndex];
  27468. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27469. continue;
  27470. }
  27471. var emitter = particleSystem.emitter;
  27472. if (!emitter.position || emitter.isEnabled()) {
  27473. this._activeParticleSystems.push(particleSystem);
  27474. particleSystem.animate();
  27475. this._renderingManager.dispatchParticles(particleSystem);
  27476. }
  27477. }
  27478. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27479. }
  27480. };
  27481. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27482. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27483. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27484. mesh.skeleton.prepare();
  27485. }
  27486. if (!mesh.computeBonesUsingShaders) {
  27487. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27488. }
  27489. }
  27490. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27491. var boundingInfo = sourceMesh.getBoundingInfo();
  27492. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27493. }
  27494. if (mesh !== undefined && mesh !== null
  27495. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27496. // Submeshes Octrees
  27497. var len;
  27498. var subMeshes;
  27499. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27500. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27501. len = intersections.length;
  27502. subMeshes = intersections.data;
  27503. }
  27504. else {
  27505. subMeshes = mesh.subMeshes;
  27506. len = subMeshes.length;
  27507. }
  27508. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27509. subMesh = subMeshes[subIndex];
  27510. this._evaluateSubMesh(subMesh, mesh);
  27511. }
  27512. }
  27513. };
  27514. /**
  27515. * Update the transform matrix to update from the current active camera
  27516. * @param force defines a boolean used to force the update even if cache is up to date
  27517. */
  27518. Scene.prototype.updateTransformMatrix = function (force) {
  27519. if (!this.activeCamera) {
  27520. return;
  27521. }
  27522. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27523. };
  27524. /**
  27525. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27526. * @param alternateCamera defines the camera to use
  27527. */
  27528. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27529. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27530. };
  27531. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27532. if (camera && camera._skipRendering) {
  27533. return;
  27534. }
  27535. var engine = this._engine;
  27536. this.activeCamera = camera;
  27537. if (!this.activeCamera)
  27538. throw new Error("Active camera not set");
  27539. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27540. // Viewport
  27541. engine.setViewport(this.activeCamera.viewport);
  27542. // Camera
  27543. this.resetCachedMaterial();
  27544. this._renderId++;
  27545. this.updateTransformMatrix();
  27546. if (camera._alternateCamera) {
  27547. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27548. this._alternateRendering = true;
  27549. }
  27550. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27551. // Meshes
  27552. this._evaluateActiveMeshes();
  27553. // Software skinning
  27554. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27555. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27556. mesh.applySkeleton(mesh.skeleton);
  27557. }
  27558. // Render targets
  27559. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27560. var needsRestoreFrameBuffer = false;
  27561. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27562. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27563. }
  27564. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27565. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27566. }
  27567. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27568. this._intermediateRendering = true;
  27569. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27570. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27571. var renderTarget = this._renderTargets.data[renderIndex];
  27572. if (renderTarget._shouldRender()) {
  27573. this._renderId++;
  27574. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27575. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27576. }
  27577. }
  27578. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27579. this._intermediateRendering = false;
  27580. this._renderId++;
  27581. needsRestoreFrameBuffer = true; // Restore back buffer
  27582. }
  27583. // Render EffecttLayer Texture
  27584. var stencilState = this._engine.getStencilBuffer();
  27585. var renderEffects = false;
  27586. var needStencil = false;
  27587. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27588. this._intermediateRendering = true;
  27589. for (var i = 0; i < this.effectLayers.length; i++) {
  27590. var effectLayer = this.effectLayers[i];
  27591. if (effectLayer.shouldRender() &&
  27592. (!effectLayer.camera ||
  27593. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27594. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27595. renderEffects = true;
  27596. needStencil = needStencil || effectLayer.needStencil();
  27597. var renderTarget = effectLayer._mainTexture;
  27598. if (renderTarget._shouldRender()) {
  27599. this._renderId++;
  27600. renderTarget.render(false, false);
  27601. needsRestoreFrameBuffer = true;
  27602. }
  27603. }
  27604. }
  27605. this._intermediateRendering = false;
  27606. this._renderId++;
  27607. }
  27608. if (needsRestoreFrameBuffer) {
  27609. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27610. }
  27611. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27612. // Prepare Frame
  27613. this.postProcessManager._prepareFrame();
  27614. // Backgrounds
  27615. var layerIndex;
  27616. var layer;
  27617. if (this.layers.length) {
  27618. engine.setDepthBuffer(false);
  27619. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27620. layer = this.layers[layerIndex];
  27621. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27622. layer.render();
  27623. }
  27624. }
  27625. engine.setDepthBuffer(true);
  27626. }
  27627. // Activate effect Layer stencil
  27628. if (needStencil) {
  27629. this._engine.setStencilBuffer(true);
  27630. }
  27631. // Render
  27632. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27633. this._renderingManager.render(null, null, true, true);
  27634. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27635. // Restore effect Layer stencil
  27636. if (needStencil) {
  27637. this._engine.setStencilBuffer(stencilState);
  27638. }
  27639. // Bounding boxes
  27640. if (this._boundingBoxRenderer) {
  27641. this._boundingBoxRenderer.render();
  27642. }
  27643. // Lens flares
  27644. if (this.lensFlaresEnabled) {
  27645. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27646. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27647. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27648. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27649. lensFlareSystem.render();
  27650. }
  27651. }
  27652. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27653. }
  27654. // Effect Layer
  27655. if (renderEffects) {
  27656. engine.setDepthBuffer(false);
  27657. for (var i = 0; i < this.effectLayers.length; i++) {
  27658. if (this.effectLayers[i].shouldRender()) {
  27659. this.effectLayers[i].render();
  27660. }
  27661. }
  27662. engine.setDepthBuffer(true);
  27663. }
  27664. // Foregrounds
  27665. if (this.layers.length) {
  27666. engine.setDepthBuffer(false);
  27667. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27668. layer = this.layers[layerIndex];
  27669. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27670. layer.render();
  27671. }
  27672. }
  27673. engine.setDepthBuffer(true);
  27674. }
  27675. // Finalize frame
  27676. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27677. // Reset some special arrays
  27678. this._renderTargets.reset();
  27679. this._alternateRendering = false;
  27680. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27681. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27682. };
  27683. Scene.prototype._processSubCameras = function (camera) {
  27684. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27685. this._renderForCamera(camera);
  27686. return;
  27687. }
  27688. // rig cameras
  27689. for (var index = 0; index < camera._rigCameras.length; index++) {
  27690. this._renderForCamera(camera._rigCameras[index], camera);
  27691. }
  27692. this.activeCamera = camera;
  27693. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27694. };
  27695. Scene.prototype._checkIntersections = function () {
  27696. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27697. var sourceMesh = this._meshesForIntersections.data[index];
  27698. if (!sourceMesh.actionManager) {
  27699. continue;
  27700. }
  27701. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27702. var action = sourceMesh.actionManager.actions[actionIndex];
  27703. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27704. var parameters = action.getTriggerParameter();
  27705. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27706. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27707. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27708. if (areIntersecting && currentIntersectionInProgress === -1) {
  27709. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27710. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27711. sourceMesh._intersectionsInProgress.push(otherMesh);
  27712. }
  27713. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27714. sourceMesh._intersectionsInProgress.push(otherMesh);
  27715. }
  27716. }
  27717. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27718. //They intersected, and now they don't.
  27719. //is this trigger an exit trigger? execute an event.
  27720. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27721. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27722. }
  27723. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27724. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27725. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27726. return otherMesh === parameterMesh;
  27727. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27728. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27729. }
  27730. }
  27731. }
  27732. }
  27733. }
  27734. };
  27735. /**
  27736. * Render the scene
  27737. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27738. */
  27739. Scene.prototype.render = function (updateCameras) {
  27740. if (updateCameras === void 0) { updateCameras = true; }
  27741. if (this.isDisposed) {
  27742. return;
  27743. }
  27744. this._activeParticles.fetchNewFrame();
  27745. this._totalVertices.fetchNewFrame();
  27746. this._activeIndices.fetchNewFrame();
  27747. this._activeBones.fetchNewFrame();
  27748. this._meshesForIntersections.reset();
  27749. this.resetCachedMaterial();
  27750. this.onBeforeAnimationsObservable.notifyObservers(this);
  27751. // Actions
  27752. if (this.actionManager) {
  27753. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27754. }
  27755. //Simplification Queue
  27756. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27757. this.simplificationQueue.executeNext();
  27758. }
  27759. if (this._engine.isDeterministicLockStep()) {
  27760. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27761. var defaultFPS = (60.0 / 1000.0);
  27762. var defaultFrameTime = 1000 / 60; // frame time in MS
  27763. if (this._physicsEngine) {
  27764. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27765. }
  27766. var stepsTaken = 0;
  27767. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27768. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27769. internalSteps = Math.min(internalSteps, maxSubSteps);
  27770. do {
  27771. this.onBeforeStepObservable.notifyObservers(this);
  27772. // Animations
  27773. this._animationRatio = defaultFrameTime * defaultFPS;
  27774. this._animate();
  27775. this.onAfterAnimationsObservable.notifyObservers(this);
  27776. // Physics
  27777. if (this._physicsEngine) {
  27778. this.onBeforePhysicsObservable.notifyObservers(this);
  27779. this._physicsEngine._step(defaultFrameTime / 1000);
  27780. this.onAfterPhysicsObservable.notifyObservers(this);
  27781. }
  27782. this.onAfterStepObservable.notifyObservers(this);
  27783. this._currentStepId++;
  27784. stepsTaken++;
  27785. deltaTime -= defaultFrameTime;
  27786. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27787. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27788. }
  27789. else {
  27790. // Animations
  27791. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27792. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27793. this._animate();
  27794. this.onAfterAnimationsObservable.notifyObservers(this);
  27795. // Physics
  27796. if (this._physicsEngine) {
  27797. this.onBeforePhysicsObservable.notifyObservers(this);
  27798. this._physicsEngine._step(deltaTime / 1000.0);
  27799. this.onAfterPhysicsObservable.notifyObservers(this);
  27800. }
  27801. }
  27802. // update gamepad manager
  27803. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27804. this._gamepadManager._checkGamepadsStatus();
  27805. }
  27806. // Update Cameras
  27807. if (updateCameras) {
  27808. if (this.activeCameras.length > 0) {
  27809. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27810. var camera = this.activeCameras[cameraIndex];
  27811. camera.update();
  27812. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27813. // rig cameras
  27814. for (var index = 0; index < camera._rigCameras.length; index++) {
  27815. camera._rigCameras[index].update();
  27816. }
  27817. }
  27818. }
  27819. }
  27820. else if (this.activeCamera) {
  27821. this.activeCamera.update();
  27822. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27823. // rig cameras
  27824. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27825. this.activeCamera._rigCameras[index].update();
  27826. }
  27827. }
  27828. }
  27829. }
  27830. // Before render
  27831. this.onBeforeRenderObservable.notifyObservers(this);
  27832. // Customs render targets
  27833. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27834. var engine = this.getEngine();
  27835. var currentActiveCamera = this.activeCamera;
  27836. if (this.renderTargetsEnabled) {
  27837. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27838. this._intermediateRendering = true;
  27839. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27840. var renderTarget = this.customRenderTargets[customIndex];
  27841. if (renderTarget._shouldRender()) {
  27842. this._renderId++;
  27843. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27844. if (!this.activeCamera)
  27845. throw new Error("Active camera not set");
  27846. // Viewport
  27847. engine.setViewport(this.activeCamera.viewport);
  27848. // Camera
  27849. this.updateTransformMatrix();
  27850. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27851. }
  27852. }
  27853. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27854. this._intermediateRendering = false;
  27855. this._renderId++;
  27856. }
  27857. // Restore back buffer
  27858. if (this.customRenderTargets.length > 0) {
  27859. engine.restoreDefaultFramebuffer();
  27860. }
  27861. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27862. this.activeCamera = currentActiveCamera;
  27863. // Procedural textures
  27864. if (this.proceduralTexturesEnabled) {
  27865. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27866. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27867. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27868. if (proceduralTexture._shouldRender()) {
  27869. proceduralTexture.render();
  27870. }
  27871. }
  27872. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27873. }
  27874. // Clear
  27875. if (this.autoClearDepthAndStencil || this.autoClear) {
  27876. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27877. }
  27878. // Shadows
  27879. if (this.shadowsEnabled) {
  27880. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27881. var light = this.lights[lightIndex];
  27882. var shadowGenerator = light.getShadowGenerator();
  27883. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27884. var shadowMap = (shadowGenerator.getShadowMap());
  27885. if (this.textures.indexOf(shadowMap) !== -1) {
  27886. this._renderTargets.push(shadowMap);
  27887. }
  27888. }
  27889. }
  27890. }
  27891. // Depth renderer
  27892. for (var key in this._depthRenderer) {
  27893. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27894. }
  27895. // Geometry renderer
  27896. if (this._geometryBufferRenderer) {
  27897. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27898. }
  27899. // RenderPipeline
  27900. if (this._postProcessRenderPipelineManager) {
  27901. this._postProcessRenderPipelineManager.update();
  27902. }
  27903. // Multi-cameras?
  27904. if (this.activeCameras.length > 0) {
  27905. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27906. if (cameraIndex > 0) {
  27907. this._engine.clear(null, false, true, true);
  27908. }
  27909. this._processSubCameras(this.activeCameras[cameraIndex]);
  27910. }
  27911. }
  27912. else {
  27913. if (!this.activeCamera) {
  27914. throw new Error("No camera defined");
  27915. }
  27916. this._processSubCameras(this.activeCamera);
  27917. }
  27918. // Intersection checks
  27919. this._checkIntersections();
  27920. // Update the audio listener attached to the camera
  27921. if (BABYLON.AudioEngine) {
  27922. this._updateAudioParameters();
  27923. }
  27924. // After render
  27925. if (this.afterRender) {
  27926. this.afterRender();
  27927. }
  27928. this.onAfterRenderObservable.notifyObservers(this);
  27929. // Cleaning
  27930. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27931. var data = this._toBeDisposed.data[index];
  27932. if (data) {
  27933. data.dispose();
  27934. }
  27935. this._toBeDisposed[index] = null;
  27936. }
  27937. this._toBeDisposed.reset();
  27938. if (this.dumpNextRenderTargets) {
  27939. this.dumpNextRenderTargets = false;
  27940. }
  27941. this._activeBones.addCount(0, true);
  27942. this._activeIndices.addCount(0, true);
  27943. this._activeParticles.addCount(0, true);
  27944. };
  27945. Scene.prototype._updateAudioParameters = function () {
  27946. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27947. return;
  27948. }
  27949. var listeningCamera;
  27950. var audioEngine = BABYLON.Engine.audioEngine;
  27951. if (this.activeCameras.length > 0) {
  27952. listeningCamera = this.activeCameras[0];
  27953. }
  27954. else {
  27955. listeningCamera = this.activeCamera;
  27956. }
  27957. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27958. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27959. // for VR cameras
  27960. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27961. listeningCamera = listeningCamera.rigCameras[0];
  27962. }
  27963. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27964. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27965. cameraDirection.normalize();
  27966. // To avoid some errors on GearVR
  27967. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27968. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27969. }
  27970. var i;
  27971. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27972. var sound = this.mainSoundTrack.soundCollection[i];
  27973. if (sound.useCustomAttenuation) {
  27974. sound.updateDistanceFromListener();
  27975. }
  27976. }
  27977. for (i = 0; i < this.soundTracks.length; i++) {
  27978. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27979. sound = this.soundTracks[i].soundCollection[j];
  27980. if (sound.useCustomAttenuation) {
  27981. sound.updateDistanceFromListener();
  27982. }
  27983. }
  27984. }
  27985. }
  27986. };
  27987. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27988. // Audio
  27989. /**
  27990. * Gets or sets if audio support is enabled
  27991. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27992. */
  27993. get: function () {
  27994. return this._audioEnabled;
  27995. },
  27996. set: function (value) {
  27997. this._audioEnabled = value;
  27998. if (BABYLON.AudioEngine) {
  27999. if (this._audioEnabled) {
  28000. this._enableAudio();
  28001. }
  28002. else {
  28003. this._disableAudio();
  28004. }
  28005. }
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. Scene.prototype._disableAudio = function () {
  28011. var i;
  28012. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28013. this.mainSoundTrack.soundCollection[i].pause();
  28014. }
  28015. for (i = 0; i < this.soundTracks.length; i++) {
  28016. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28017. this.soundTracks[i].soundCollection[j].pause();
  28018. }
  28019. }
  28020. };
  28021. Scene.prototype._enableAudio = function () {
  28022. var i;
  28023. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28024. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28025. this.mainSoundTrack.soundCollection[i].play();
  28026. }
  28027. }
  28028. for (i = 0; i < this.soundTracks.length; i++) {
  28029. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28030. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28031. this.soundTracks[i].soundCollection[j].play();
  28032. }
  28033. }
  28034. }
  28035. };
  28036. Object.defineProperty(Scene.prototype, "headphone", {
  28037. /**
  28038. * Gets or sets if audio will be output to headphones
  28039. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28040. */
  28041. get: function () {
  28042. return this._headphone;
  28043. },
  28044. set: function (value) {
  28045. this._headphone = value;
  28046. if (BABYLON.AudioEngine) {
  28047. if (this._headphone) {
  28048. this._switchAudioModeForHeadphones();
  28049. }
  28050. else {
  28051. this._switchAudioModeForNormalSpeakers();
  28052. }
  28053. }
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Scene.prototype._switchAudioModeForHeadphones = function () {
  28059. this.mainSoundTrack.switchPanningModelToHRTF();
  28060. for (var i = 0; i < this.soundTracks.length; i++) {
  28061. this.soundTracks[i].switchPanningModelToHRTF();
  28062. }
  28063. };
  28064. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28065. this.mainSoundTrack.switchPanningModelToEqualPower();
  28066. for (var i = 0; i < this.soundTracks.length; i++) {
  28067. this.soundTracks[i].switchPanningModelToEqualPower();
  28068. }
  28069. };
  28070. /**
  28071. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28072. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28073. * @returns the created depth renderer
  28074. */
  28075. Scene.prototype.enableDepthRenderer = function (camera) {
  28076. camera = camera || this.activeCamera;
  28077. if (!camera) {
  28078. throw "No camera available to enable depth renderer";
  28079. }
  28080. if (!this._depthRenderer[camera.id]) {
  28081. var textureType = 0;
  28082. if (this._engine.getCaps().textureHalfFloatRender) {
  28083. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28084. }
  28085. else if (this._engine.getCaps().textureFloatRender) {
  28086. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28087. }
  28088. else {
  28089. throw "Depth renderer does not support int texture type";
  28090. }
  28091. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28092. }
  28093. return this._depthRenderer[camera.id];
  28094. };
  28095. /**
  28096. * Disables a depth renderer for a given camera
  28097. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28098. */
  28099. Scene.prototype.disableDepthRenderer = function (camera) {
  28100. camera = camera || this.activeCamera;
  28101. if (!camera || !this._depthRenderer[camera.id]) {
  28102. return;
  28103. }
  28104. this._depthRenderer[camera.id].dispose();
  28105. delete this._depthRenderer[camera.id];
  28106. };
  28107. /**
  28108. * Enables a GeometryBufferRender and associates it with the scene
  28109. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28110. * @returns the GeometryBufferRenderer
  28111. */
  28112. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28113. if (ratio === void 0) { ratio = 1; }
  28114. if (this._geometryBufferRenderer) {
  28115. return this._geometryBufferRenderer;
  28116. }
  28117. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28118. if (!this._geometryBufferRenderer.isSupported) {
  28119. this._geometryBufferRenderer = null;
  28120. }
  28121. return this._geometryBufferRenderer;
  28122. };
  28123. /**
  28124. * Disables the GeometryBufferRender associated with the scene
  28125. */
  28126. Scene.prototype.disableGeometryBufferRenderer = function () {
  28127. if (!this._geometryBufferRenderer) {
  28128. return;
  28129. }
  28130. this._geometryBufferRenderer.dispose();
  28131. this._geometryBufferRenderer = null;
  28132. };
  28133. /**
  28134. * Freeze all materials
  28135. * A frozen material will not be updatable but should be faster to render
  28136. */
  28137. Scene.prototype.freezeMaterials = function () {
  28138. for (var i = 0; i < this.materials.length; i++) {
  28139. this.materials[i].freeze();
  28140. }
  28141. };
  28142. /**
  28143. * Unfreeze all materials
  28144. * A frozen material will not be updatable but should be faster to render
  28145. */
  28146. Scene.prototype.unfreezeMaterials = function () {
  28147. for (var i = 0; i < this.materials.length; i++) {
  28148. this.materials[i].unfreeze();
  28149. }
  28150. };
  28151. /**
  28152. * Releases all held ressources
  28153. */
  28154. Scene.prototype.dispose = function () {
  28155. this.beforeRender = null;
  28156. this.afterRender = null;
  28157. this.skeletons = [];
  28158. this.morphTargetManagers = [];
  28159. this.importedMeshesFiles = new Array();
  28160. this.stopAllAnimations();
  28161. this.resetCachedMaterial();
  28162. for (var key in this._depthRenderer) {
  28163. this._depthRenderer[key].dispose();
  28164. }
  28165. if (this._gamepadManager) {
  28166. this._gamepadManager.dispose();
  28167. this._gamepadManager = null;
  28168. }
  28169. // Smart arrays
  28170. if (this.activeCamera) {
  28171. this.activeCamera._activeMeshes.dispose();
  28172. this.activeCamera = null;
  28173. }
  28174. this._activeMeshes.dispose();
  28175. this._renderingManager.dispose();
  28176. this._processedMaterials.dispose();
  28177. this._activeParticleSystems.dispose();
  28178. this._activeSkeletons.dispose();
  28179. this._softwareSkinnedMeshes.dispose();
  28180. this._renderTargets.dispose();
  28181. this._registeredForLateAnimationBindings.dispose();
  28182. if (this._boundingBoxRenderer) {
  28183. this._boundingBoxRenderer.dispose();
  28184. }
  28185. this._meshesForIntersections.dispose();
  28186. this._toBeDisposed.dispose();
  28187. // Abort active requests
  28188. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28189. var request = _a[_i];
  28190. request.abort();
  28191. }
  28192. // Debug layer
  28193. if (this._debugLayer) {
  28194. this._debugLayer.hide();
  28195. }
  28196. // Events
  28197. this.onDisposeObservable.notifyObservers(this);
  28198. this.onDisposeObservable.clear();
  28199. this.onBeforeRenderObservable.clear();
  28200. this.onAfterRenderObservable.clear();
  28201. this.onBeforeRenderTargetsRenderObservable.clear();
  28202. this.onAfterRenderTargetsRenderObservable.clear();
  28203. this.onAfterStepObservable.clear();
  28204. this.onBeforeStepObservable.clear();
  28205. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28206. this.onAfterActiveMeshesEvaluationObservable.clear();
  28207. this.onBeforeParticlesRenderingObservable.clear();
  28208. this.onAfterParticlesRenderingObservable.clear();
  28209. this.onBeforeSpritesRenderingObservable.clear();
  28210. this.onAfterSpritesRenderingObservable.clear();
  28211. this.onBeforeDrawPhaseObservable.clear();
  28212. this.onAfterDrawPhaseObservable.clear();
  28213. this.onBeforePhysicsObservable.clear();
  28214. this.onAfterPhysicsObservable.clear();
  28215. this.onBeforeAnimationsObservable.clear();
  28216. this.onAfterAnimationsObservable.clear();
  28217. this.onDataLoadedObservable.clear();
  28218. this.detachControl();
  28219. // Release sounds & sounds tracks
  28220. if (BABYLON.AudioEngine) {
  28221. this.disposeSounds();
  28222. }
  28223. // VR Helper
  28224. if (this.VRHelper) {
  28225. this.VRHelper.dispose();
  28226. }
  28227. // Detach cameras
  28228. var canvas = this._engine.getRenderingCanvas();
  28229. if (canvas) {
  28230. var index;
  28231. for (index = 0; index < this.cameras.length; index++) {
  28232. this.cameras[index].detachControl(canvas);
  28233. }
  28234. }
  28235. // Release animation groups
  28236. while (this.animationGroups.length) {
  28237. this.animationGroups[0].dispose();
  28238. }
  28239. // Release lights
  28240. while (this.lights.length) {
  28241. this.lights[0].dispose();
  28242. }
  28243. // Release meshes
  28244. while (this.meshes.length) {
  28245. this.meshes[0].dispose(true);
  28246. }
  28247. while (this.transformNodes.length) {
  28248. this.removeTransformNode(this.transformNodes[0]);
  28249. }
  28250. // Release cameras
  28251. while (this.cameras.length) {
  28252. this.cameras[0].dispose();
  28253. }
  28254. // Release materials
  28255. if (this.defaultMaterial) {
  28256. this.defaultMaterial.dispose();
  28257. }
  28258. while (this.multiMaterials.length) {
  28259. this.multiMaterials[0].dispose();
  28260. }
  28261. while (this.materials.length) {
  28262. this.materials[0].dispose();
  28263. }
  28264. // Release particles
  28265. while (this.particleSystems.length) {
  28266. this.particleSystems[0].dispose();
  28267. }
  28268. // Release sprites
  28269. while (this.spriteManagers.length) {
  28270. this.spriteManagers[0].dispose();
  28271. }
  28272. // Release postProcesses
  28273. while (this.postProcesses.length) {
  28274. this.postProcesses[0].dispose();
  28275. }
  28276. // Release layers
  28277. while (this.layers.length) {
  28278. this.layers[0].dispose();
  28279. }
  28280. while (this.effectLayers.length) {
  28281. this.effectLayers[0].dispose();
  28282. }
  28283. // Release textures
  28284. while (this.textures.length) {
  28285. this.textures[0].dispose();
  28286. }
  28287. // Release UBO
  28288. this._sceneUbo.dispose();
  28289. if (this._alternateSceneUbo) {
  28290. this._alternateSceneUbo.dispose();
  28291. }
  28292. // Post-processes
  28293. this.postProcessManager.dispose();
  28294. if (this._postProcessRenderPipelineManager) {
  28295. this._postProcessRenderPipelineManager.dispose();
  28296. }
  28297. // Physics
  28298. if (this._physicsEngine) {
  28299. this.disablePhysicsEngine();
  28300. }
  28301. // Remove from engine
  28302. index = this._engine.scenes.indexOf(this);
  28303. if (index > -1) {
  28304. this._engine.scenes.splice(index, 1);
  28305. }
  28306. this._engine.wipeCaches(true);
  28307. this._isDisposed = true;
  28308. };
  28309. Object.defineProperty(Scene.prototype, "isDisposed", {
  28310. /**
  28311. * Gets if the scene is already disposed
  28312. */
  28313. get: function () {
  28314. return this._isDisposed;
  28315. },
  28316. enumerable: true,
  28317. configurable: true
  28318. });
  28319. /**
  28320. * Releases sounds & soundtracks
  28321. */
  28322. Scene.prototype.disposeSounds = function () {
  28323. if (!this._mainSoundTrack) {
  28324. return;
  28325. }
  28326. this.mainSoundTrack.dispose();
  28327. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28328. this.soundTracks[scIndex].dispose();
  28329. }
  28330. };
  28331. /**
  28332. * Call this function to reduce memory footprint of the scene.
  28333. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28334. */
  28335. Scene.prototype.clearCachedVertexData = function () {
  28336. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28337. var mesh = this.meshes[meshIndex];
  28338. var geometry = mesh.geometry;
  28339. if (geometry) {
  28340. geometry._indices = [];
  28341. for (var vbName in geometry._vertexBuffers) {
  28342. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28343. continue;
  28344. }
  28345. geometry._vertexBuffers[vbName]._buffer._data = null;
  28346. }
  28347. }
  28348. }
  28349. };
  28350. /**
  28351. * This function will remove the local cached buffer data from texture.
  28352. * It will save memory but will prevent the texture from being rebuilt
  28353. */
  28354. Scene.prototype.cleanCachedTextureBuffer = function () {
  28355. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28356. var baseTexture = _a[_i];
  28357. var buffer = baseTexture._buffer;
  28358. if (buffer) {
  28359. baseTexture._buffer = null;
  28360. }
  28361. }
  28362. };
  28363. // Octrees
  28364. /**
  28365. * Get the world extend vectors with an optional filter
  28366. *
  28367. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28368. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28369. */
  28370. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28371. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28372. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28373. filterPredicate = filterPredicate || (function () { return true; });
  28374. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28375. mesh.computeWorldMatrix(true);
  28376. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28377. return;
  28378. }
  28379. var boundingInfo = mesh.getBoundingInfo();
  28380. var minBox = boundingInfo.boundingBox.minimumWorld;
  28381. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28382. BABYLON.Tools.CheckExtends(minBox, min, max);
  28383. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28384. });
  28385. return {
  28386. min: min,
  28387. max: max
  28388. };
  28389. };
  28390. /**
  28391. * Creates or updates the octree used to boost selection (picking)
  28392. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28393. * @param maxCapacity defines the maximum capacity per leaf
  28394. * @param maxDepth defines the maximum depth of the octree
  28395. * @returns an octree of AbstractMesh
  28396. */
  28397. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28398. if (maxCapacity === void 0) { maxCapacity = 64; }
  28399. if (maxDepth === void 0) { maxDepth = 2; }
  28400. if (!this._selectionOctree) {
  28401. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28402. }
  28403. var worldExtends = this.getWorldExtends();
  28404. // Update octree
  28405. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28406. return this._selectionOctree;
  28407. };
  28408. // Picking
  28409. /**
  28410. * Creates a ray that can be used to pick in the scene
  28411. * @param x defines the x coordinate of the origin (on-screen)
  28412. * @param y defines the y coordinate of the origin (on-screen)
  28413. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28414. * @param camera defines the camera to use for the picking
  28415. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28416. * @returns a Ray
  28417. */
  28418. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28419. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28420. var result = BABYLON.Ray.Zero();
  28421. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28422. return result;
  28423. };
  28424. /**
  28425. * Creates a ray that can be used to pick in the scene
  28426. * @param x defines the x coordinate of the origin (on-screen)
  28427. * @param y defines the y coordinate of the origin (on-screen)
  28428. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28429. * @param result defines the ray where to store the picking ray
  28430. * @param camera defines the camera to use for the picking
  28431. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28432. * @returns the current scene
  28433. */
  28434. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28435. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28436. var engine = this._engine;
  28437. if (!camera) {
  28438. if (!this.activeCamera)
  28439. throw new Error("Active camera not set");
  28440. camera = this.activeCamera;
  28441. }
  28442. var cameraViewport = camera.viewport;
  28443. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28444. // Moving coordinates to local viewport world
  28445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28447. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28448. return this;
  28449. };
  28450. /**
  28451. * Creates a ray that can be used to pick in the scene
  28452. * @param x defines the x coordinate of the origin (on-screen)
  28453. * @param y defines the y coordinate of the origin (on-screen)
  28454. * @param camera defines the camera to use for the picking
  28455. * @returns a Ray
  28456. */
  28457. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28458. var result = BABYLON.Ray.Zero();
  28459. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28460. return result;
  28461. };
  28462. /**
  28463. * Creates a ray that can be used to pick in the scene
  28464. * @param x defines the x coordinate of the origin (on-screen)
  28465. * @param y defines the y coordinate of the origin (on-screen)
  28466. * @param result defines the ray where to store the picking ray
  28467. * @param camera defines the camera to use for the picking
  28468. * @returns the current scene
  28469. */
  28470. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28471. if (!BABYLON.PickingInfo) {
  28472. return this;
  28473. }
  28474. var engine = this._engine;
  28475. if (!camera) {
  28476. if (!this.activeCamera)
  28477. throw new Error("Active camera not set");
  28478. camera = this.activeCamera;
  28479. }
  28480. var cameraViewport = camera.viewport;
  28481. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28482. var identity = BABYLON.Matrix.Identity();
  28483. // Moving coordinates to local viewport world
  28484. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28485. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28486. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28487. return this;
  28488. };
  28489. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28490. if (!BABYLON.PickingInfo) {
  28491. return null;
  28492. }
  28493. var pickingInfo = null;
  28494. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28495. var mesh = this.meshes[meshIndex];
  28496. if (predicate) {
  28497. if (!predicate(mesh)) {
  28498. continue;
  28499. }
  28500. }
  28501. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28502. continue;
  28503. }
  28504. var world = mesh.getWorldMatrix();
  28505. var ray = rayFunction(world);
  28506. var result = mesh.intersects(ray, fastCheck);
  28507. if (!result || !result.hit)
  28508. continue;
  28509. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28510. continue;
  28511. pickingInfo = result;
  28512. if (fastCheck) {
  28513. break;
  28514. }
  28515. }
  28516. return pickingInfo || new BABYLON.PickingInfo();
  28517. };
  28518. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28519. if (!BABYLON.PickingInfo) {
  28520. return null;
  28521. }
  28522. var pickingInfos = new Array();
  28523. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28524. var mesh = this.meshes[meshIndex];
  28525. if (predicate) {
  28526. if (!predicate(mesh)) {
  28527. continue;
  28528. }
  28529. }
  28530. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28531. continue;
  28532. }
  28533. var world = mesh.getWorldMatrix();
  28534. var ray = rayFunction(world);
  28535. var result = mesh.intersects(ray, false);
  28536. if (!result || !result.hit)
  28537. continue;
  28538. pickingInfos.push(result);
  28539. }
  28540. return pickingInfos;
  28541. };
  28542. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28543. if (!BABYLON.PickingInfo) {
  28544. return null;
  28545. }
  28546. var pickingInfo = null;
  28547. if (!camera) {
  28548. if (!this.activeCamera) {
  28549. return null;
  28550. }
  28551. camera = this.activeCamera;
  28552. }
  28553. if (this.spriteManagers.length > 0) {
  28554. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28555. var spriteManager = this.spriteManagers[spriteIndex];
  28556. if (!spriteManager.isPickable) {
  28557. continue;
  28558. }
  28559. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28560. if (!result || !result.hit)
  28561. continue;
  28562. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28563. continue;
  28564. pickingInfo = result;
  28565. if (fastCheck) {
  28566. break;
  28567. }
  28568. }
  28569. }
  28570. return pickingInfo || new BABYLON.PickingInfo();
  28571. };
  28572. /** Launch a ray to try to pick a mesh in the scene
  28573. * @param x position on screen
  28574. * @param y position on screen
  28575. * @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
  28576. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28577. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28578. * @returns a PickingInfo
  28579. */
  28580. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28581. var _this = this;
  28582. if (!BABYLON.PickingInfo) {
  28583. return null;
  28584. }
  28585. var result = this._internalPick(function (world) {
  28586. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28587. return _this._tempPickingRay;
  28588. }, predicate, fastCheck);
  28589. if (result) {
  28590. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28591. }
  28592. return result;
  28593. };
  28594. /** Launch a ray to try to pick a sprite in the scene
  28595. * @param x position on screen
  28596. * @param y position on screen
  28597. * @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
  28598. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28599. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28600. * @returns a PickingInfo
  28601. */
  28602. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28603. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28604. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28605. };
  28606. /** Use the given ray to pick a mesh in the scene
  28607. * @param ray The ray to use to pick meshes
  28608. * @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
  28609. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28610. * @returns a PickingInfo
  28611. */
  28612. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28613. var _this = this;
  28614. var result = this._internalPick(function (world) {
  28615. if (!_this._pickWithRayInverseMatrix) {
  28616. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28617. }
  28618. world.invertToRef(_this._pickWithRayInverseMatrix);
  28619. if (!_this._cachedRayForTransform) {
  28620. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28621. }
  28622. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28623. return _this._cachedRayForTransform;
  28624. }, predicate, fastCheck);
  28625. if (result) {
  28626. result.ray = ray;
  28627. }
  28628. return result;
  28629. };
  28630. /**
  28631. * Launch a ray to try to pick a mesh in the scene
  28632. * @param x X position on screen
  28633. * @param y Y position on screen
  28634. * @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
  28635. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28636. * @returns an array of PickingInfo
  28637. */
  28638. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28639. var _this = this;
  28640. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28641. };
  28642. /**
  28643. * Launch a ray to try to pick a mesh in the scene
  28644. * @param ray Ray to use
  28645. * @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
  28646. * @returns an array of PickingInfo
  28647. */
  28648. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28649. var _this = this;
  28650. return this._internalMultiPick(function (world) {
  28651. if (!_this._pickWithRayInverseMatrix) {
  28652. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28653. }
  28654. world.invertToRef(_this._pickWithRayInverseMatrix);
  28655. if (!_this._cachedRayForTransform) {
  28656. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28657. }
  28658. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28659. return _this._cachedRayForTransform;
  28660. }, predicate);
  28661. };
  28662. /**
  28663. * Force the value of meshUnderPointer
  28664. * @param mesh defines the mesh to use
  28665. */
  28666. Scene.prototype.setPointerOverMesh = function (mesh) {
  28667. if (this._pointerOverMesh === mesh) {
  28668. return;
  28669. }
  28670. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28671. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28672. }
  28673. this._pointerOverMesh = mesh;
  28674. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28675. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28676. }
  28677. };
  28678. /**
  28679. * Gets the mesh under the pointer
  28680. * @returns a Mesh or null if no mesh is under the pointer
  28681. */
  28682. Scene.prototype.getPointerOverMesh = function () {
  28683. return this._pointerOverMesh;
  28684. };
  28685. /**
  28686. * Force the sprite under the pointer
  28687. * @param sprite defines the sprite to use
  28688. */
  28689. Scene.prototype.setPointerOverSprite = function (sprite) {
  28690. if (this._pointerOverSprite === sprite) {
  28691. return;
  28692. }
  28693. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28694. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28695. }
  28696. this._pointerOverSprite = sprite;
  28697. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28698. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28699. }
  28700. };
  28701. /**
  28702. * Gets the sprite under the pointer
  28703. * @returns a Sprite or null if no sprite is under the pointer
  28704. */
  28705. Scene.prototype.getPointerOverSprite = function () {
  28706. return this._pointerOverSprite;
  28707. };
  28708. // Physics
  28709. /**
  28710. * Gets the current physics engine
  28711. * @returns a PhysicsEngine or null if none attached
  28712. */
  28713. Scene.prototype.getPhysicsEngine = function () {
  28714. return this._physicsEngine;
  28715. };
  28716. /**
  28717. * Enables physics to the current scene
  28718. * @param gravity defines the scene's gravity for the physics engine
  28719. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28720. * @return a boolean indicating if the physics engine was initialized
  28721. */
  28722. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28723. if (gravity === void 0) { gravity = null; }
  28724. if (this._physicsEngine) {
  28725. return true;
  28726. }
  28727. try {
  28728. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28729. return true;
  28730. }
  28731. catch (e) {
  28732. BABYLON.Tools.Error(e.message);
  28733. return false;
  28734. }
  28735. };
  28736. /**
  28737. * Disables and disposes the physics engine associated with the scene
  28738. */
  28739. Scene.prototype.disablePhysicsEngine = function () {
  28740. if (!this._physicsEngine) {
  28741. return;
  28742. }
  28743. this._physicsEngine.dispose();
  28744. this._physicsEngine = null;
  28745. };
  28746. /**
  28747. * Gets a boolean indicating if there is an active physics engine
  28748. * @returns a boolean indicating if there is an active physics engine
  28749. */
  28750. Scene.prototype.isPhysicsEnabled = function () {
  28751. return this._physicsEngine !== undefined;
  28752. };
  28753. /**
  28754. * Deletes a physics compound impostor
  28755. * @param compound defines the compound to delete
  28756. */
  28757. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28758. var mesh = compound.parts[0].mesh;
  28759. if (mesh.physicsImpostor) {
  28760. mesh.physicsImpostor.dispose( /*true*/);
  28761. mesh.physicsImpostor = null;
  28762. }
  28763. };
  28764. // Misc.
  28765. /** @hidden */
  28766. Scene.prototype._rebuildGeometries = function () {
  28767. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28768. var geometry = _a[_i];
  28769. geometry._rebuild();
  28770. }
  28771. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28772. var mesh = _c[_b];
  28773. mesh._rebuild();
  28774. }
  28775. if (this.postProcessManager) {
  28776. this.postProcessManager._rebuild();
  28777. }
  28778. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28779. var layer = _e[_d];
  28780. layer._rebuild();
  28781. }
  28782. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28783. var effectLayer = _g[_f];
  28784. effectLayer._rebuild();
  28785. }
  28786. if (this._boundingBoxRenderer) {
  28787. this._boundingBoxRenderer._rebuild();
  28788. }
  28789. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28790. var system = _j[_h];
  28791. system.rebuild();
  28792. }
  28793. if (this._postProcessRenderPipelineManager) {
  28794. this._postProcessRenderPipelineManager._rebuild();
  28795. }
  28796. };
  28797. /** @hidden */
  28798. Scene.prototype._rebuildTextures = function () {
  28799. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28800. var texture = _a[_i];
  28801. texture._rebuild();
  28802. }
  28803. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28804. };
  28805. /**
  28806. * Creates a default light for the scene.
  28807. * @param replace Whether to replace the existing lights in the scene.
  28808. */
  28809. Scene.prototype.createDefaultLight = function (replace) {
  28810. if (replace === void 0) { replace = false; }
  28811. // Dispose existing light in replace mode.
  28812. if (replace) {
  28813. if (this.lights) {
  28814. for (var i = 0; i < this.lights.length; i++) {
  28815. this.lights[i].dispose();
  28816. }
  28817. }
  28818. }
  28819. // Light
  28820. if (this.lights.length === 0) {
  28821. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28822. }
  28823. };
  28824. /**
  28825. * Creates a default camera for the scene.
  28826. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28827. * @param replace Whether to replace the existing active camera in the scene.
  28828. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28829. */
  28830. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28831. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28832. if (replace === void 0) { replace = false; }
  28833. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28834. // Dispose existing camera in replace mode.
  28835. if (replace) {
  28836. if (this.activeCamera) {
  28837. this.activeCamera.dispose();
  28838. this.activeCamera = null;
  28839. }
  28840. }
  28841. // Camera
  28842. if (!this.activeCamera) {
  28843. var worldExtends = this.getWorldExtends();
  28844. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28845. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28846. var camera;
  28847. var radius = worldSize.length() * 1.5;
  28848. // empty scene scenario!
  28849. if (!isFinite(radius)) {
  28850. radius = 1;
  28851. worldCenter.copyFromFloats(0, 0, 0);
  28852. }
  28853. if (createArcRotateCamera) {
  28854. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28855. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28856. arcRotateCamera.wheelPrecision = 100 / radius;
  28857. camera = arcRotateCamera;
  28858. }
  28859. else {
  28860. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28861. freeCamera.setTarget(worldCenter);
  28862. camera = freeCamera;
  28863. }
  28864. camera.minZ = radius * 0.01;
  28865. camera.maxZ = radius * 1000;
  28866. camera.speed = radius * 0.2;
  28867. this.activeCamera = camera;
  28868. var canvas = this.getEngine().getRenderingCanvas();
  28869. if (attachCameraControls && canvas) {
  28870. camera.attachControl(canvas);
  28871. }
  28872. }
  28873. };
  28874. /**
  28875. * Creates a default camera and a default light
  28876. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28877. * @param replace defines if the camera and/or light will replace the existing ones
  28878. * @param attachCameraControls defines if attachControl will be called on the new camera
  28879. */
  28880. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28881. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28882. if (replace === void 0) { replace = false; }
  28883. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28884. this.createDefaultLight(replace);
  28885. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28886. };
  28887. /**
  28888. * Creates a new sky box
  28889. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28890. * @param environmentTexture defines the texture to use as environment texture
  28891. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28892. * @param scale defines the overall scale of the skybox
  28893. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28894. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28895. * @returns a new mesh holding the sky box
  28896. */
  28897. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28898. if (pbr === void 0) { pbr = false; }
  28899. if (scale === void 0) { scale = 1000; }
  28900. if (blur === void 0) { blur = 0; }
  28901. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28902. if (!environmentTexture) {
  28903. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28904. return null;
  28905. }
  28906. if (setGlobalEnvTexture) {
  28907. if (environmentTexture) {
  28908. this.environmentTexture = environmentTexture;
  28909. }
  28910. }
  28911. // Skybox
  28912. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28913. if (pbr) {
  28914. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28915. hdrSkyboxMaterial.backFaceCulling = false;
  28916. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28917. if (hdrSkyboxMaterial.reflectionTexture) {
  28918. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28919. }
  28920. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28921. hdrSkyboxMaterial.disableLighting = true;
  28922. hdrSkyboxMaterial.twoSidedLighting = true;
  28923. hdrSkybox.infiniteDistance = true;
  28924. hdrSkybox.material = hdrSkyboxMaterial;
  28925. }
  28926. else {
  28927. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28928. skyboxMaterial.backFaceCulling = false;
  28929. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28930. if (skyboxMaterial.reflectionTexture) {
  28931. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28932. }
  28933. skyboxMaterial.disableLighting = true;
  28934. hdrSkybox.infiniteDistance = true;
  28935. hdrSkybox.material = skyboxMaterial;
  28936. }
  28937. return hdrSkybox;
  28938. };
  28939. /**
  28940. * Creates a new environment
  28941. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28942. * @param options defines the options you can use to configure the environment
  28943. * @returns the new EnvironmentHelper
  28944. */
  28945. Scene.prototype.createDefaultEnvironment = function (options) {
  28946. if (BABYLON.EnvironmentHelper) {
  28947. return new BABYLON.EnvironmentHelper(options, this);
  28948. }
  28949. return null;
  28950. };
  28951. /**
  28952. * Creates a new VREXperienceHelper
  28953. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28954. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28955. * @returns a new VREXperienceHelper
  28956. */
  28957. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28958. if (webVROptions === void 0) { webVROptions = {}; }
  28959. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28960. };
  28961. // Tags
  28962. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28963. if (tagsQuery === undefined) {
  28964. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28965. return list;
  28966. }
  28967. var listByTags = [];
  28968. forEach = forEach || (function (item) { return; });
  28969. for (var i in list) {
  28970. var item = list[i];
  28971. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28972. listByTags.push(item);
  28973. forEach(item);
  28974. }
  28975. }
  28976. return listByTags;
  28977. };
  28978. /**
  28979. * Get a list of meshes by tags
  28980. * @param tagsQuery defines the tags query to use
  28981. * @param forEach defines a predicate used to filter results
  28982. * @returns an array of Mesh
  28983. */
  28984. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28985. return this._getByTags(this.meshes, tagsQuery, forEach);
  28986. };
  28987. /**
  28988. * Get a list of cameras by tags
  28989. * @param tagsQuery defines the tags query to use
  28990. * @param forEach defines a predicate used to filter results
  28991. * @returns an array of Camera
  28992. */
  28993. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28994. return this._getByTags(this.cameras, tagsQuery, forEach);
  28995. };
  28996. /**
  28997. * Get a list of lights by tags
  28998. * @param tagsQuery defines the tags query to use
  28999. * @param forEach defines a predicate used to filter results
  29000. * @returns an array of Light
  29001. */
  29002. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29003. return this._getByTags(this.lights, tagsQuery, forEach);
  29004. };
  29005. /**
  29006. * Get a list of materials by tags
  29007. * @param tagsQuery defines the tags query to use
  29008. * @param forEach defines a predicate used to filter results
  29009. * @returns an array of Material
  29010. */
  29011. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29012. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29013. };
  29014. /**
  29015. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29016. * This allowed control for front to back rendering or reversly depending of the special needs.
  29017. *
  29018. * @param renderingGroupId The rendering group id corresponding to its index
  29019. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29020. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29021. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29022. */
  29023. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29024. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29025. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29026. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29027. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29028. };
  29029. /**
  29030. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29031. *
  29032. * @param renderingGroupId The rendering group id corresponding to its index
  29033. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29034. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29035. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29036. */
  29037. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29038. if (depth === void 0) { depth = true; }
  29039. if (stencil === void 0) { stencil = true; }
  29040. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29041. };
  29042. /**
  29043. * Will flag all materials as dirty to trigger new shader compilation
  29044. * @param flag defines the flag used to specify which material part must be marked as dirty
  29045. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29046. */
  29047. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29048. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29049. var material = _a[_i];
  29050. if (predicate && !predicate(material)) {
  29051. continue;
  29052. }
  29053. material.markAsDirty(flag);
  29054. }
  29055. };
  29056. /** @hidden */
  29057. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29058. var _this = this;
  29059. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29060. this._activeRequests.push(request);
  29061. request.onCompleteObservable.add(function (request) {
  29062. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29063. });
  29064. return request;
  29065. };
  29066. /** @hidden */
  29067. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29068. var _this = this;
  29069. return new Promise(function (resolve, reject) {
  29070. _this._loadFile(url, function (data) {
  29071. resolve(data);
  29072. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29073. reject(exception);
  29074. });
  29075. });
  29076. };
  29077. // Statics
  29078. Scene._FOGMODE_NONE = 0;
  29079. Scene._FOGMODE_EXP = 1;
  29080. Scene._FOGMODE_EXP2 = 2;
  29081. Scene._FOGMODE_LINEAR = 3;
  29082. Scene._uniqueIdCounter = 0;
  29083. /**
  29084. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29085. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29086. */
  29087. Scene.MinDeltaTime = 1.0;
  29088. /**
  29089. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29090. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29091. */
  29092. Scene.MaxDeltaTime = 1000.0;
  29093. /** The distance in pixel that you have to move to prevent some events */
  29094. Scene.DragMovementThreshold = 10; // in pixels
  29095. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29096. Scene.LongPressDelay = 500; // in milliseconds
  29097. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29098. Scene.DoubleClickDelay = 300; // in milliseconds
  29099. /** If you need to check double click without raising a single click at first click, enable this flag */
  29100. Scene.ExclusiveDoubleClickMode = false;
  29101. return Scene;
  29102. }());
  29103. BABYLON.Scene = Scene;
  29104. })(BABYLON || (BABYLON = {}));
  29105. //# sourceMappingURL=babylon.scene.js.map
  29106. var BABYLON;
  29107. (function (BABYLON) {
  29108. /**
  29109. * Set of assets to keep when moving a scene into an asset container.
  29110. */
  29111. var KeepAssets = /** @class */ (function () {
  29112. function KeepAssets() {
  29113. /**
  29114. * Cameras to keep.
  29115. */
  29116. this.cameras = new Array();
  29117. /**
  29118. * Lights to keep.
  29119. */
  29120. this.lights = new Array();
  29121. /**
  29122. * Meshes to keep.
  29123. */
  29124. this.meshes = new Array();
  29125. /**
  29126. * Skeletons to keep.
  29127. */
  29128. this.skeletons = new Array();
  29129. /**
  29130. * ParticleSystems to keep.
  29131. */
  29132. this.particleSystems = new Array();
  29133. /**
  29134. * Animations to keep.
  29135. */
  29136. this.animations = new Array();
  29137. /**
  29138. * AnimationGroups to keep.
  29139. */
  29140. this.animationGroups = new Array();
  29141. /**
  29142. * MultiMaterials to keep.
  29143. */
  29144. this.multiMaterials = new Array();
  29145. /**
  29146. * Materials to keep.
  29147. */
  29148. this.materials = new Array();
  29149. /**
  29150. * MorphTargetManagers to keep.
  29151. */
  29152. this.morphTargetManagers = new Array();
  29153. /**
  29154. * Geometries to keep.
  29155. */
  29156. this.geometries = new Array();
  29157. /**
  29158. * TransformNodes to keep.
  29159. */
  29160. this.transformNodes = new Array();
  29161. /**
  29162. * LensFlareSystems to keep.
  29163. */
  29164. this.lensFlareSystems = new Array();
  29165. /**
  29166. * ShadowGenerators to keep.
  29167. */
  29168. this.shadowGenerators = new Array();
  29169. /**
  29170. * ActionManagers to keep.
  29171. */
  29172. this.actionManagers = new Array();
  29173. /**
  29174. * Sounds to keep.
  29175. */
  29176. this.sounds = new Array();
  29177. /**
  29178. * Textures to keep.
  29179. */
  29180. this.textures = new Array();
  29181. /**
  29182. * Effect layers to keep.
  29183. */
  29184. this.effectLayers = new Array();
  29185. }
  29186. return KeepAssets;
  29187. }());
  29188. BABYLON.KeepAssets = KeepAssets;
  29189. /**
  29190. * Container with a set of assets that can be added or removed from a scene.
  29191. */
  29192. var AssetContainer = /** @class */ (function () {
  29193. /**
  29194. * Instantiates an AssetContainer.
  29195. * @param scene The scene the AssetContainer belongs to.
  29196. */
  29197. function AssetContainer(scene) {
  29198. // Objects
  29199. /**
  29200. * Cameras populated in the container.
  29201. */
  29202. this.cameras = new Array();
  29203. /**
  29204. * Lights populated in the container.
  29205. */
  29206. this.lights = new Array();
  29207. /**
  29208. * Meshes populated in the container.
  29209. */
  29210. this.meshes = new Array();
  29211. /**
  29212. * Skeletons populated in the container.
  29213. */
  29214. this.skeletons = new Array();
  29215. /**
  29216. * ParticleSystems populated in the container.
  29217. */
  29218. this.particleSystems = new Array();
  29219. /**
  29220. * Animations populated in the container.
  29221. */
  29222. this.animations = new Array();
  29223. /**
  29224. * AnimationGroups populated in the container.
  29225. */
  29226. this.animationGroups = new Array();
  29227. /**
  29228. * MultiMaterials populated in the container.
  29229. */
  29230. this.multiMaterials = new Array();
  29231. /**
  29232. * Materials populated in the container.
  29233. */
  29234. this.materials = new Array();
  29235. /**
  29236. * MorphTargetManagers populated in the container.
  29237. */
  29238. this.morphTargetManagers = new Array();
  29239. /**
  29240. * Geometries populated in the container.
  29241. */
  29242. this.geometries = new Array();
  29243. /**
  29244. * TransformNodes populated in the container.
  29245. */
  29246. this.transformNodes = new Array();
  29247. /**
  29248. * LensFlareSystems populated in the container.
  29249. */
  29250. this.lensFlareSystems = new Array();
  29251. /**
  29252. * ShadowGenerators populated in the container.
  29253. */
  29254. this.shadowGenerators = new Array();
  29255. /**
  29256. * ActionManagers populated in the container.
  29257. */
  29258. this.actionManagers = new Array();
  29259. /**
  29260. * Sounds populated in the container.
  29261. */
  29262. this.sounds = new Array();
  29263. /**
  29264. * Textures populated in the container.
  29265. */
  29266. this.textures = new Array();
  29267. /**
  29268. * Effect layers populated in the container.
  29269. */
  29270. this.effectLayers = new Array();
  29271. this.scene = scene;
  29272. }
  29273. /**
  29274. * Adds all the assets from the container to the scene.
  29275. */
  29276. AssetContainer.prototype.addAllToScene = function () {
  29277. var _this = this;
  29278. this.cameras.forEach(function (o) {
  29279. _this.scene.addCamera(o);
  29280. });
  29281. this.lights.forEach(function (o) {
  29282. _this.scene.addLight(o);
  29283. });
  29284. this.meshes.forEach(function (o) {
  29285. _this.scene.addMesh(o);
  29286. });
  29287. this.skeletons.forEach(function (o) {
  29288. _this.scene.addSkeleton(o);
  29289. });
  29290. this.particleSystems.forEach(function (o) {
  29291. _this.scene.addParticleSystem(o);
  29292. });
  29293. this.animations.forEach(function (o) {
  29294. _this.scene.addAnimation(o);
  29295. });
  29296. this.animationGroups.forEach(function (o) {
  29297. _this.scene.addAnimationGroup(o);
  29298. });
  29299. this.multiMaterials.forEach(function (o) {
  29300. _this.scene.addMultiMaterial(o);
  29301. });
  29302. this.materials.forEach(function (o) {
  29303. _this.scene.addMaterial(o);
  29304. });
  29305. this.morphTargetManagers.forEach(function (o) {
  29306. _this.scene.addMorphTargetManager(o);
  29307. });
  29308. this.geometries.forEach(function (o) {
  29309. _this.scene.addGeometry(o);
  29310. });
  29311. this.transformNodes.forEach(function (o) {
  29312. _this.scene.addTransformNode(o);
  29313. });
  29314. this.lensFlareSystems.forEach(function (o) {
  29315. _this.scene.addLensFlareSystem(o);
  29316. });
  29317. this.actionManagers.forEach(function (o) {
  29318. _this.scene.addActionManager(o);
  29319. });
  29320. this.sounds.forEach(function (o) {
  29321. o.play();
  29322. o.autoplay = true;
  29323. _this.scene.mainSoundTrack.AddSound(o);
  29324. });
  29325. this.textures.forEach(function (o) {
  29326. _this.scene.addTexture(o);
  29327. });
  29328. this.effectLayers.forEach(function (o) {
  29329. _this.scene.addEffectLayer(o);
  29330. });
  29331. };
  29332. /**
  29333. * Removes all the assets in the container from the scene
  29334. */
  29335. AssetContainer.prototype.removeAllFromScene = function () {
  29336. var _this = this;
  29337. this.cameras.forEach(function (o) {
  29338. _this.scene.removeCamera(o);
  29339. });
  29340. this.lights.forEach(function (o) {
  29341. _this.scene.removeLight(o);
  29342. });
  29343. this.meshes.forEach(function (o) {
  29344. _this.scene.removeMesh(o);
  29345. });
  29346. this.skeletons.forEach(function (o) {
  29347. _this.scene.removeSkeleton(o);
  29348. });
  29349. this.particleSystems.forEach(function (o) {
  29350. _this.scene.removeParticleSystem(o);
  29351. });
  29352. this.animations.forEach(function (o) {
  29353. _this.scene.removeAnimation(o);
  29354. });
  29355. this.animationGroups.forEach(function (o) {
  29356. _this.scene.removeAnimationGroup(o);
  29357. });
  29358. this.multiMaterials.forEach(function (o) {
  29359. _this.scene.removeMultiMaterial(o);
  29360. });
  29361. this.materials.forEach(function (o) {
  29362. _this.scene.removeMaterial(o);
  29363. });
  29364. this.morphTargetManagers.forEach(function (o) {
  29365. _this.scene.removeMorphTargetManager(o);
  29366. });
  29367. this.geometries.forEach(function (o) {
  29368. _this.scene.removeGeometry(o);
  29369. });
  29370. this.transformNodes.forEach(function (o) {
  29371. _this.scene.removeTransformNode(o);
  29372. });
  29373. this.lensFlareSystems.forEach(function (o) {
  29374. _this.scene.removeLensFlareSystem(o);
  29375. });
  29376. this.actionManagers.forEach(function (o) {
  29377. _this.scene.removeActionManager(o);
  29378. });
  29379. this.sounds.forEach(function (o) {
  29380. o.stop();
  29381. o.autoplay = false;
  29382. _this.scene.mainSoundTrack.RemoveSound(o);
  29383. });
  29384. this.textures.forEach(function (o) {
  29385. _this.scene.removeTexture(o);
  29386. });
  29387. this.effectLayers.forEach(function (o) {
  29388. _this.scene.removeEffectLayer(o);
  29389. });
  29390. };
  29391. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29392. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29393. var asset = sourceAssets_1[_i];
  29394. var move = true;
  29395. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29396. var keepAsset = keepAssets_1[_a];
  29397. if (asset === keepAsset) {
  29398. move = false;
  29399. break;
  29400. }
  29401. }
  29402. if (move) {
  29403. targetAssets.push(asset);
  29404. }
  29405. }
  29406. };
  29407. /**
  29408. * Removes all the assets contained in the scene and adds them to the container.
  29409. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29410. */
  29411. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29412. if (keepAssets === undefined) {
  29413. keepAssets = new KeepAssets();
  29414. }
  29415. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29416. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29417. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29418. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29419. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29420. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29421. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29422. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29423. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29424. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29425. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29426. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29427. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29428. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29429. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29430. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29431. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29432. this.removeAllFromScene();
  29433. };
  29434. /**
  29435. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29436. * @returns the root mesh
  29437. */
  29438. AssetContainer.prototype.createRootMesh = function () {
  29439. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29440. this.meshes.forEach(function (m) {
  29441. if (!m.parent) {
  29442. rootMesh.addChild(m);
  29443. }
  29444. });
  29445. this.meshes.unshift(rootMesh);
  29446. return rootMesh;
  29447. };
  29448. return AssetContainer;
  29449. }());
  29450. BABYLON.AssetContainer = AssetContainer;
  29451. })(BABYLON || (BABYLON = {}));
  29452. //# sourceMappingURL=babylon.assetContainer.js.map
  29453. var BABYLON;
  29454. (function (BABYLON) {
  29455. var Buffer = /** @class */ (function () {
  29456. /**
  29457. * Constructor
  29458. * @param engine the engine
  29459. * @param data the data to use for this buffer
  29460. * @param updatable whether the data is updatable
  29461. * @param stride the stride (optional)
  29462. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29463. * @param instanced whether the buffer is instanced (optional)
  29464. * @param useBytes set to true if the stride in in bytes (optional)
  29465. */
  29466. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29467. if (stride === void 0) { stride = 0; }
  29468. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29469. if (instanced === void 0) { instanced = false; }
  29470. if (useBytes === void 0) { useBytes = false; }
  29471. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29472. this._engine = engine.getScene().getEngine();
  29473. }
  29474. else {
  29475. this._engine = engine;
  29476. }
  29477. this._updatable = updatable;
  29478. this._instanced = instanced;
  29479. this._data = data;
  29480. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29481. if (!postponeInternalCreation) { // by default
  29482. this.create();
  29483. }
  29484. }
  29485. /**
  29486. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29487. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29488. * @param offset defines offset in the buffer (0 by default)
  29489. * @param size defines the size in floats of attributes (position is 3 for instance)
  29490. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29491. * @param instanced defines if the vertex buffer contains indexed data
  29492. * @param useBytes defines if the offset and stride are in bytes
  29493. * @returns the new vertex buffer
  29494. */
  29495. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29496. if (useBytes === void 0) { useBytes = false; }
  29497. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29498. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29499. // a lot of these parameters are ignored as they are overriden by the buffer
  29500. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29501. };
  29502. // Properties
  29503. Buffer.prototype.isUpdatable = function () {
  29504. return this._updatable;
  29505. };
  29506. Buffer.prototype.getData = function () {
  29507. return this._data;
  29508. };
  29509. Buffer.prototype.getBuffer = function () {
  29510. return this._buffer;
  29511. };
  29512. /**
  29513. * Gets the stride in float32 units (i.e. byte stride / 4).
  29514. * May not be an integer if the byte stride is not divisible by 4.
  29515. * DEPRECATED. Use byteStride instead.
  29516. * @returns the stride in float32 units
  29517. */
  29518. Buffer.prototype.getStrideSize = function () {
  29519. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29520. };
  29521. // Methods
  29522. Buffer.prototype.create = function (data) {
  29523. if (data === void 0) { data = null; }
  29524. if (!data && this._buffer) {
  29525. return; // nothing to do
  29526. }
  29527. data = data || this._data;
  29528. if (!data) {
  29529. return;
  29530. }
  29531. if (!this._buffer) { // create buffer
  29532. if (this._updatable) {
  29533. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29534. this._data = data;
  29535. }
  29536. else {
  29537. this._buffer = this._engine.createVertexBuffer(data);
  29538. }
  29539. }
  29540. else if (this._updatable) { // update buffer
  29541. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29542. this._data = data;
  29543. }
  29544. };
  29545. Buffer.prototype._rebuild = function () {
  29546. this._buffer = null;
  29547. this.create(this._data);
  29548. };
  29549. Buffer.prototype.update = function (data) {
  29550. this.create(data);
  29551. };
  29552. /**
  29553. * Updates the data directly.
  29554. * @param data the new data
  29555. * @param offset the new offset
  29556. * @param vertexCount the vertex count (optional)
  29557. * @param useBytes set to true if the offset is in bytes
  29558. */
  29559. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29560. if (useBytes === void 0) { useBytes = false; }
  29561. if (!this._buffer) {
  29562. return;
  29563. }
  29564. if (this._updatable) { // update buffer
  29565. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29566. this._data = null;
  29567. }
  29568. };
  29569. Buffer.prototype.dispose = function () {
  29570. if (!this._buffer) {
  29571. return;
  29572. }
  29573. if (this._engine._releaseBuffer(this._buffer)) {
  29574. this._buffer = null;
  29575. }
  29576. };
  29577. return Buffer;
  29578. }());
  29579. BABYLON.Buffer = Buffer;
  29580. })(BABYLON || (BABYLON = {}));
  29581. //# sourceMappingURL=babylon.buffer.js.map
  29582. var BABYLON;
  29583. (function (BABYLON) {
  29584. var VertexBuffer = /** @class */ (function () {
  29585. /**
  29586. * Constructor
  29587. * @param engine the engine
  29588. * @param data the data to use for this vertex buffer
  29589. * @param kind the vertex buffer kind
  29590. * @param updatable whether the data is updatable
  29591. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29592. * @param stride the stride (optional)
  29593. * @param instanced whether the buffer is instanced (optional)
  29594. * @param offset the offset of the data (optional)
  29595. * @param size the number of components (optional)
  29596. * @param type the type of the component (optional)
  29597. * @param normalized whether the data contains normalized data (optional)
  29598. * @param useBytes set to true if stride and offset are in bytes (optional)
  29599. */
  29600. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29601. if (normalized === void 0) { normalized = false; }
  29602. if (useBytes === void 0) { useBytes = false; }
  29603. if (data instanceof BABYLON.Buffer) {
  29604. this._buffer = data;
  29605. this._ownsBuffer = false;
  29606. }
  29607. else {
  29608. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29609. this._ownsBuffer = true;
  29610. }
  29611. this._kind = kind;
  29612. if (type == undefined) {
  29613. var data_1 = this.getData();
  29614. this.type = VertexBuffer.FLOAT;
  29615. if (data_1 instanceof Int8Array)
  29616. this.type = VertexBuffer.BYTE;
  29617. else if (data_1 instanceof Uint8Array)
  29618. this.type = VertexBuffer.UNSIGNED_BYTE;
  29619. else if (data_1 instanceof Int16Array)
  29620. this.type = VertexBuffer.SHORT;
  29621. else if (data_1 instanceof Uint16Array)
  29622. this.type = VertexBuffer.UNSIGNED_SHORT;
  29623. else if (data_1 instanceof Int32Array)
  29624. this.type = VertexBuffer.INT;
  29625. else if (data_1 instanceof Uint32Array)
  29626. this.type = VertexBuffer.UNSIGNED_INT;
  29627. }
  29628. else {
  29629. this.type = type;
  29630. }
  29631. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29632. if (useBytes) {
  29633. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29634. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29635. this.byteOffset = offset || 0;
  29636. }
  29637. else {
  29638. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29639. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29640. this.byteOffset = (offset || 0) * typeByteLength;
  29641. }
  29642. this.normalized = normalized;
  29643. this._instanced = instanced !== undefined ? instanced : false;
  29644. this._instanceDivisor = instanced ? 1 : 0;
  29645. }
  29646. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29647. /**
  29648. * Gets or sets the instance divisor when in instanced mode
  29649. */
  29650. get: function () {
  29651. return this._instanceDivisor;
  29652. },
  29653. set: function (value) {
  29654. this._instanceDivisor = value;
  29655. if (value == 0) {
  29656. this._instanced = false;
  29657. }
  29658. else {
  29659. this._instanced = true;
  29660. }
  29661. },
  29662. enumerable: true,
  29663. configurable: true
  29664. });
  29665. VertexBuffer.prototype._rebuild = function () {
  29666. if (!this._buffer) {
  29667. return;
  29668. }
  29669. this._buffer._rebuild();
  29670. };
  29671. /**
  29672. * Returns the kind of the VertexBuffer (string).
  29673. */
  29674. VertexBuffer.prototype.getKind = function () {
  29675. return this._kind;
  29676. };
  29677. // Properties
  29678. /**
  29679. * Boolean : is the VertexBuffer updatable ?
  29680. */
  29681. VertexBuffer.prototype.isUpdatable = function () {
  29682. return this._buffer.isUpdatable();
  29683. };
  29684. /**
  29685. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29686. */
  29687. VertexBuffer.prototype.getData = function () {
  29688. return this._buffer.getData();
  29689. };
  29690. /**
  29691. * Returns the WebGLBuffer associated to the VertexBuffer.
  29692. */
  29693. VertexBuffer.prototype.getBuffer = function () {
  29694. return this._buffer.getBuffer();
  29695. };
  29696. /**
  29697. * Returns the stride as a multiple of the type byte length.
  29698. * DEPRECATED. Use byteStride instead.
  29699. */
  29700. VertexBuffer.prototype.getStrideSize = function () {
  29701. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29702. };
  29703. /**
  29704. * Returns the offset as a multiple of the type byte length.
  29705. * DEPRECATED. Use byteOffset instead.
  29706. */
  29707. VertexBuffer.prototype.getOffset = function () {
  29708. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29709. };
  29710. /**
  29711. * Returns the number of components per vertex attribute (integer).
  29712. */
  29713. VertexBuffer.prototype.getSize = function () {
  29714. return this._size;
  29715. };
  29716. /**
  29717. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29718. */
  29719. VertexBuffer.prototype.getIsInstanced = function () {
  29720. return this._instanced;
  29721. };
  29722. /**
  29723. * Returns the instancing divisor, zero for non-instanced (integer).
  29724. */
  29725. VertexBuffer.prototype.getInstanceDivisor = function () {
  29726. return this._instanceDivisor;
  29727. };
  29728. // Methods
  29729. /**
  29730. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29731. * Returns the created WebGLBuffer.
  29732. */
  29733. VertexBuffer.prototype.create = function (data) {
  29734. return this._buffer.create(data);
  29735. };
  29736. /**
  29737. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29738. * This function will create a new buffer if the current one is not updatable
  29739. * Returns the updated WebGLBuffer.
  29740. */
  29741. VertexBuffer.prototype.update = function (data) {
  29742. return this._buffer.update(data);
  29743. };
  29744. /**
  29745. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29746. * Returns the directly updated WebGLBuffer.
  29747. * @param data the new data
  29748. * @param offset the new offset
  29749. * @param useBytes set to true if the offset is in bytes
  29750. */
  29751. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29752. if (useBytes === void 0) { useBytes = false; }
  29753. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29754. };
  29755. /**
  29756. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29757. */
  29758. VertexBuffer.prototype.dispose = function () {
  29759. if (this._ownsBuffer) {
  29760. this._buffer.dispose();
  29761. }
  29762. };
  29763. /**
  29764. * Enumerates each value of this vertex buffer as numbers.
  29765. * @param count the number of values to enumerate
  29766. * @param callback the callback function called for each value
  29767. */
  29768. VertexBuffer.prototype.forEach = function (count, callback) {
  29769. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29770. };
  29771. Object.defineProperty(VertexBuffer, "PositionKind", {
  29772. get: function () {
  29773. return VertexBuffer._PositionKind;
  29774. },
  29775. enumerable: true,
  29776. configurable: true
  29777. });
  29778. Object.defineProperty(VertexBuffer, "NormalKind", {
  29779. get: function () {
  29780. return VertexBuffer._NormalKind;
  29781. },
  29782. enumerable: true,
  29783. configurable: true
  29784. });
  29785. Object.defineProperty(VertexBuffer, "TangentKind", {
  29786. get: function () {
  29787. return VertexBuffer._TangentKind;
  29788. },
  29789. enumerable: true,
  29790. configurable: true
  29791. });
  29792. Object.defineProperty(VertexBuffer, "UVKind", {
  29793. get: function () {
  29794. return VertexBuffer._UVKind;
  29795. },
  29796. enumerable: true,
  29797. configurable: true
  29798. });
  29799. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29800. get: function () {
  29801. return VertexBuffer._UV2Kind;
  29802. },
  29803. enumerable: true,
  29804. configurable: true
  29805. });
  29806. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29807. get: function () {
  29808. return VertexBuffer._UV3Kind;
  29809. },
  29810. enumerable: true,
  29811. configurable: true
  29812. });
  29813. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29814. get: function () {
  29815. return VertexBuffer._UV4Kind;
  29816. },
  29817. enumerable: true,
  29818. configurable: true
  29819. });
  29820. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29821. get: function () {
  29822. return VertexBuffer._UV5Kind;
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29828. get: function () {
  29829. return VertexBuffer._UV6Kind;
  29830. },
  29831. enumerable: true,
  29832. configurable: true
  29833. });
  29834. Object.defineProperty(VertexBuffer, "ColorKind", {
  29835. get: function () {
  29836. return VertexBuffer._ColorKind;
  29837. },
  29838. enumerable: true,
  29839. configurable: true
  29840. });
  29841. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29842. get: function () {
  29843. return VertexBuffer._MatricesIndicesKind;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29849. get: function () {
  29850. return VertexBuffer._MatricesWeightsKind;
  29851. },
  29852. enumerable: true,
  29853. configurable: true
  29854. });
  29855. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29856. get: function () {
  29857. return VertexBuffer._MatricesIndicesExtraKind;
  29858. },
  29859. enumerable: true,
  29860. configurable: true
  29861. });
  29862. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29863. get: function () {
  29864. return VertexBuffer._MatricesWeightsExtraKind;
  29865. },
  29866. enumerable: true,
  29867. configurable: true
  29868. });
  29869. /**
  29870. * Deduces the stride given a kind.
  29871. * @param kind The kind string to deduce
  29872. * @returns The deduced stride
  29873. */
  29874. VertexBuffer.DeduceStride = function (kind) {
  29875. switch (kind) {
  29876. case VertexBuffer.UVKind:
  29877. case VertexBuffer.UV2Kind:
  29878. case VertexBuffer.UV3Kind:
  29879. case VertexBuffer.UV4Kind:
  29880. case VertexBuffer.UV5Kind:
  29881. case VertexBuffer.UV6Kind:
  29882. return 2;
  29883. case VertexBuffer.NormalKind:
  29884. case VertexBuffer.PositionKind:
  29885. return 3;
  29886. case VertexBuffer.ColorKind:
  29887. case VertexBuffer.MatricesIndicesKind:
  29888. case VertexBuffer.MatricesIndicesExtraKind:
  29889. case VertexBuffer.MatricesWeightsKind:
  29890. case VertexBuffer.MatricesWeightsExtraKind:
  29891. case VertexBuffer.TangentKind:
  29892. return 4;
  29893. default:
  29894. throw new Error("Invalid kind '" + kind + "'");
  29895. }
  29896. };
  29897. /**
  29898. * Gets the byte length of the given type.
  29899. * @param type the type
  29900. * @returns the number of bytes
  29901. */
  29902. VertexBuffer.GetTypeByteLength = function (type) {
  29903. switch (type) {
  29904. case VertexBuffer.BYTE:
  29905. case VertexBuffer.UNSIGNED_BYTE:
  29906. return 1;
  29907. case VertexBuffer.SHORT:
  29908. case VertexBuffer.UNSIGNED_SHORT:
  29909. return 2;
  29910. case VertexBuffer.INT:
  29911. case VertexBuffer.FLOAT:
  29912. return 4;
  29913. default:
  29914. throw new Error("Invalid type '" + type + "'");
  29915. }
  29916. };
  29917. /**
  29918. * Enumerates each value of the given parameters as numbers.
  29919. * @param data the data to enumerate
  29920. * @param byteOffset the byte offset of the data
  29921. * @param byteStride the byte stride of the data
  29922. * @param componentCount the number of components per element
  29923. * @param componentType the type of the component
  29924. * @param count the total number of components
  29925. * @param normalized whether the data is normalized
  29926. * @param callback the callback function called for each value
  29927. */
  29928. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29929. if (data instanceof Array) {
  29930. var offset = byteOffset / 4;
  29931. var stride = byteStride / 4;
  29932. for (var index = 0; index < count; index += componentCount) {
  29933. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29934. callback(data[offset + componentIndex], index + componentIndex);
  29935. }
  29936. offset += stride;
  29937. }
  29938. }
  29939. else {
  29940. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29941. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29942. for (var index = 0; index < count; index += componentCount) {
  29943. var componentByteOffset = byteOffset;
  29944. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29945. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29946. callback(value, index + componentIndex);
  29947. componentByteOffset += componentByteLength;
  29948. }
  29949. byteOffset += byteStride;
  29950. }
  29951. }
  29952. };
  29953. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29954. switch (type) {
  29955. case VertexBuffer.BYTE: {
  29956. var value = dataView.getInt8(byteOffset);
  29957. if (normalized) {
  29958. value = Math.max(value / 127, -1);
  29959. }
  29960. return value;
  29961. }
  29962. case VertexBuffer.UNSIGNED_BYTE: {
  29963. var value = dataView.getUint8(byteOffset);
  29964. if (normalized) {
  29965. value = value / 255;
  29966. }
  29967. return value;
  29968. }
  29969. case VertexBuffer.SHORT: {
  29970. var value = dataView.getInt16(byteOffset, true);
  29971. if (normalized) {
  29972. value = Math.max(value / 16383, -1);
  29973. }
  29974. return value;
  29975. }
  29976. case VertexBuffer.UNSIGNED_SHORT: {
  29977. var value = dataView.getUint16(byteOffset, true);
  29978. if (normalized) {
  29979. value = value / 65535;
  29980. }
  29981. return value;
  29982. }
  29983. case VertexBuffer.FLOAT: {
  29984. return dataView.getFloat32(byteOffset, true);
  29985. }
  29986. default: {
  29987. throw new Error("Invalid component type " + type);
  29988. }
  29989. }
  29990. };
  29991. /**
  29992. * The byte type.
  29993. */
  29994. VertexBuffer.BYTE = 5120;
  29995. /**
  29996. * The unsigned byte type.
  29997. */
  29998. VertexBuffer.UNSIGNED_BYTE = 5121;
  29999. /**
  30000. * The short type.
  30001. */
  30002. VertexBuffer.SHORT = 5122;
  30003. /**
  30004. * The unsigned short type.
  30005. */
  30006. VertexBuffer.UNSIGNED_SHORT = 5123;
  30007. /**
  30008. * The integer type.
  30009. */
  30010. VertexBuffer.INT = 5124;
  30011. /**
  30012. * The unsigned integer type.
  30013. */
  30014. VertexBuffer.UNSIGNED_INT = 5125;
  30015. /**
  30016. * The float type.
  30017. */
  30018. VertexBuffer.FLOAT = 5126;
  30019. // Enums
  30020. VertexBuffer._PositionKind = "position";
  30021. VertexBuffer._NormalKind = "normal";
  30022. VertexBuffer._TangentKind = "tangent";
  30023. VertexBuffer._UVKind = "uv";
  30024. VertexBuffer._UV2Kind = "uv2";
  30025. VertexBuffer._UV3Kind = "uv3";
  30026. VertexBuffer._UV4Kind = "uv4";
  30027. VertexBuffer._UV5Kind = "uv5";
  30028. VertexBuffer._UV6Kind = "uv6";
  30029. VertexBuffer._ColorKind = "color";
  30030. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30031. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30032. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30033. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30034. return VertexBuffer;
  30035. }());
  30036. BABYLON.VertexBuffer = VertexBuffer;
  30037. })(BABYLON || (BABYLON = {}));
  30038. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30039. var BABYLON;
  30040. (function (BABYLON) {
  30041. /**
  30042. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30043. */
  30044. var DummyInternalTextureTracker = /** @class */ (function () {
  30045. function DummyInternalTextureTracker() {
  30046. /**
  30047. * Gets or set the previous tracker in the list
  30048. */
  30049. this.previous = null;
  30050. /**
  30051. * Gets or set the next tracker in the list
  30052. */
  30053. this.next = null;
  30054. }
  30055. return DummyInternalTextureTracker;
  30056. }());
  30057. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30058. })(BABYLON || (BABYLON = {}));
  30059. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30060. var BABYLON;
  30061. (function (BABYLON) {
  30062. /**
  30063. * Class used to store data associated with WebGL texture data for the engine
  30064. * This class should not be used directly
  30065. */
  30066. var InternalTexture = /** @class */ (function () {
  30067. /**
  30068. * Creates a new InternalTexture
  30069. * @param engine defines the engine to use
  30070. * @param dataSource defines the type of data that will be used
  30071. */
  30072. function InternalTexture(engine, dataSource) {
  30073. /**
  30074. * Observable called when the texture is loaded
  30075. */
  30076. this.onLoadedObservable = new BABYLON.Observable();
  30077. /**
  30078. * Gets or set the previous tracker in the list
  30079. */
  30080. this.previous = null;
  30081. /**
  30082. * Gets or set the next tracker in the list
  30083. */
  30084. this.next = null;
  30085. // Private
  30086. /** @hidden */
  30087. this._initialSlot = -1;
  30088. /** @hidden */
  30089. this._designatedSlot = -1;
  30090. /** @hidden */
  30091. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30092. /** @hidden */
  30093. this._comparisonFunction = 0;
  30094. /** @hidden */
  30095. this._isRGBD = false;
  30096. /** @hidden */
  30097. this._references = 1;
  30098. this._engine = engine;
  30099. this._dataSource = dataSource;
  30100. this._webGLTexture = engine._createTexture();
  30101. }
  30102. /**
  30103. * Gets the Engine the texture belongs to.
  30104. * @returns The babylon engine
  30105. */
  30106. InternalTexture.prototype.getEngine = function () {
  30107. return this._engine;
  30108. };
  30109. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30110. /**
  30111. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30112. */
  30113. get: function () {
  30114. return this._dataSource;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. /**
  30120. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30121. */
  30122. InternalTexture.prototype.incrementReferences = function () {
  30123. this._references++;
  30124. };
  30125. /**
  30126. * Change the size of the texture (not the size of the content)
  30127. * @param width defines the new width
  30128. * @param height defines the new height
  30129. * @param depth defines the new depth (1 by default)
  30130. */
  30131. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30132. if (depth === void 0) { depth = 1; }
  30133. this.width = width;
  30134. this.height = height;
  30135. this.depth = depth;
  30136. this.baseWidth = width;
  30137. this.baseHeight = height;
  30138. this.baseDepth = depth;
  30139. this._size = width * height * depth;
  30140. };
  30141. /** @hidden */
  30142. InternalTexture.prototype._rebuild = function () {
  30143. var _this = this;
  30144. var proxy;
  30145. this.isReady = false;
  30146. this._cachedCoordinatesMode = null;
  30147. this._cachedWrapU = null;
  30148. this._cachedWrapV = null;
  30149. this._cachedAnisotropicFilteringLevel = null;
  30150. switch (this._dataSource) {
  30151. case InternalTexture.DATASOURCE_TEMP:
  30152. return;
  30153. case InternalTexture.DATASOURCE_URL:
  30154. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30155. _this.isReady = true;
  30156. }, null, this._buffer, undefined, this.format);
  30157. proxy._swapAndDie(this);
  30158. return;
  30159. case InternalTexture.DATASOURCE_RAW:
  30160. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30161. proxy._swapAndDie(this);
  30162. this.isReady = true;
  30163. return;
  30164. case InternalTexture.DATASOURCE_RAW3D:
  30165. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30166. proxy._swapAndDie(this);
  30167. this.isReady = true;
  30168. return;
  30169. case InternalTexture.DATASOURCE_DYNAMIC:
  30170. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30171. proxy._swapAndDie(this);
  30172. // The engine will make sure to update content so no need to flag it as isReady = true
  30173. return;
  30174. case InternalTexture.DATASOURCE_RENDERTARGET:
  30175. var options = new BABYLON.RenderTargetCreationOptions();
  30176. options.generateDepthBuffer = this._generateDepthBuffer;
  30177. options.generateMipMaps = this.generateMipMaps;
  30178. options.generateStencilBuffer = this._generateStencilBuffer;
  30179. options.samplingMode = this.samplingMode;
  30180. options.type = this.type;
  30181. if (this.isCube) {
  30182. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30183. }
  30184. else {
  30185. var size = {
  30186. width: this.width,
  30187. height: this.height
  30188. };
  30189. proxy = this._engine.createRenderTargetTexture(size, options);
  30190. }
  30191. proxy._swapAndDie(this);
  30192. this.isReady = true;
  30193. return;
  30194. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30195. var depthTextureOptions = {
  30196. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30197. comparisonFunction: this._comparisonFunction,
  30198. generateStencil: this._generateStencilBuffer,
  30199. isCube: this.isCube
  30200. };
  30201. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30202. proxy._swapAndDie(this);
  30203. this.isReady = true;
  30204. return;
  30205. case InternalTexture.DATASOURCE_CUBE:
  30206. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30207. _this.isReady = true;
  30208. }, null, this.format, this._extension);
  30209. proxy._swapAndDie(this);
  30210. return;
  30211. case InternalTexture.DATASOURCE_CUBERAW:
  30212. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30213. proxy._swapAndDie(this);
  30214. this.isReady = true;
  30215. return;
  30216. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30217. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30218. if (proxy) {
  30219. proxy._swapAndDie(_this);
  30220. }
  30221. _this.isReady = true;
  30222. }, null, this.format, this._extension);
  30223. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30224. return;
  30225. }
  30226. };
  30227. InternalTexture.prototype._swapAndDie = function (target) {
  30228. target._webGLTexture = this._webGLTexture;
  30229. if (this._framebuffer) {
  30230. target._framebuffer = this._framebuffer;
  30231. }
  30232. if (this._depthStencilBuffer) {
  30233. target._depthStencilBuffer = this._depthStencilBuffer;
  30234. }
  30235. if (this._lodTextureHigh) {
  30236. if (target._lodTextureHigh) {
  30237. target._lodTextureHigh.dispose();
  30238. }
  30239. target._lodTextureHigh = this._lodTextureHigh;
  30240. }
  30241. if (this._lodTextureMid) {
  30242. if (target._lodTextureMid) {
  30243. target._lodTextureMid.dispose();
  30244. }
  30245. target._lodTextureMid = this._lodTextureMid;
  30246. }
  30247. if (this._lodTextureLow) {
  30248. if (target._lodTextureLow) {
  30249. target._lodTextureLow.dispose();
  30250. }
  30251. target._lodTextureLow = this._lodTextureLow;
  30252. }
  30253. var cache = this._engine.getLoadedTexturesCache();
  30254. var index = cache.indexOf(this);
  30255. if (index !== -1) {
  30256. cache.splice(index, 1);
  30257. }
  30258. };
  30259. /**
  30260. * Dispose the current allocated resources
  30261. */
  30262. InternalTexture.prototype.dispose = function () {
  30263. if (!this._webGLTexture) {
  30264. return;
  30265. }
  30266. this._references--;
  30267. if (this._references === 0) {
  30268. this._engine._releaseTexture(this);
  30269. this._webGLTexture = null;
  30270. this.previous = null;
  30271. this.next = null;
  30272. }
  30273. };
  30274. /**
  30275. * The source of the texture data is unknown
  30276. */
  30277. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30278. /**
  30279. * Texture data comes from an URL
  30280. */
  30281. InternalTexture.DATASOURCE_URL = 1;
  30282. /**
  30283. * Texture data is only used for temporary storage
  30284. */
  30285. InternalTexture.DATASOURCE_TEMP = 2;
  30286. /**
  30287. * Texture data comes from raw data (ArrayBuffer)
  30288. */
  30289. InternalTexture.DATASOURCE_RAW = 3;
  30290. /**
  30291. * Texture content is dynamic (video or dynamic texture)
  30292. */
  30293. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30294. /**
  30295. * Texture content is generated by rendering to it
  30296. */
  30297. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30298. /**
  30299. * Texture content is part of a multi render target process
  30300. */
  30301. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30302. /**
  30303. * Texture data comes from a cube data file
  30304. */
  30305. InternalTexture.DATASOURCE_CUBE = 7;
  30306. /**
  30307. * Texture data comes from a raw cube data
  30308. */
  30309. InternalTexture.DATASOURCE_CUBERAW = 8;
  30310. /**
  30311. * Texture data come from a prefiltered cube data file
  30312. */
  30313. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30314. /**
  30315. * Texture content is raw 3D data
  30316. */
  30317. InternalTexture.DATASOURCE_RAW3D = 10;
  30318. /**
  30319. * Texture content is a depth texture
  30320. */
  30321. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30322. return InternalTexture;
  30323. }());
  30324. BABYLON.InternalTexture = InternalTexture;
  30325. })(BABYLON || (BABYLON = {}));
  30326. //# sourceMappingURL=babylon.internalTexture.js.map
  30327. var BABYLON;
  30328. (function (BABYLON) {
  30329. var BaseTexture = /** @class */ (function () {
  30330. function BaseTexture(scene) {
  30331. this._hasAlpha = false;
  30332. this.getAlphaFromRGB = false;
  30333. this.level = 1;
  30334. this.coordinatesIndex = 0;
  30335. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30336. /**
  30337. * | Value | Type | Description |
  30338. * | ----- | ------------------ | ----------- |
  30339. * | 0 | CLAMP_ADDRESSMODE | |
  30340. * | 1 | WRAP_ADDRESSMODE | |
  30341. * | 2 | MIRROR_ADDRESSMODE | |
  30342. */
  30343. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30344. /**
  30345. * | Value | Type | Description |
  30346. * | ----- | ------------------ | ----------- |
  30347. * | 0 | CLAMP_ADDRESSMODE | |
  30348. * | 1 | WRAP_ADDRESSMODE | |
  30349. * | 2 | MIRROR_ADDRESSMODE | |
  30350. */
  30351. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30352. /**
  30353. * | Value | Type | Description |
  30354. * | ----- | ------------------ | ----------- |
  30355. * | 0 | CLAMP_ADDRESSMODE | |
  30356. * | 1 | WRAP_ADDRESSMODE | |
  30357. * | 2 | MIRROR_ADDRESSMODE | |
  30358. */
  30359. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30360. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30361. this.isCube = false;
  30362. this.is3D = false;
  30363. this.gammaSpace = true;
  30364. this.invertZ = false;
  30365. this.lodLevelInAlpha = false;
  30366. this.isRenderTarget = false;
  30367. this.animations = new Array();
  30368. /**
  30369. * An event triggered when the texture is disposed.
  30370. */
  30371. this.onDisposeObservable = new BABYLON.Observable();
  30372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30373. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30374. if (this._scene) {
  30375. this._scene.textures.push(this);
  30376. }
  30377. this._uid = null;
  30378. }
  30379. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30380. get: function () {
  30381. return this._hasAlpha;
  30382. },
  30383. set: function (value) {
  30384. if (this._hasAlpha === value) {
  30385. return;
  30386. }
  30387. this._hasAlpha = value;
  30388. if (this._scene) {
  30389. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30390. }
  30391. },
  30392. enumerable: true,
  30393. configurable: true
  30394. });
  30395. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30396. get: function () {
  30397. return this._coordinatesMode;
  30398. },
  30399. /**
  30400. * How a texture is mapped.
  30401. *
  30402. * | Value | Type | Description |
  30403. * | ----- | ----------------------------------- | ----------- |
  30404. * | 0 | EXPLICIT_MODE | |
  30405. * | 1 | SPHERICAL_MODE | |
  30406. * | 2 | PLANAR_MODE | |
  30407. * | 3 | CUBIC_MODE | |
  30408. * | 4 | PROJECTION_MODE | |
  30409. * | 5 | SKYBOX_MODE | |
  30410. * | 6 | INVCUBIC_MODE | |
  30411. * | 7 | EQUIRECTANGULAR_MODE | |
  30412. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30413. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30414. */
  30415. set: function (value) {
  30416. if (this._coordinatesMode === value) {
  30417. return;
  30418. }
  30419. this._coordinatesMode = value;
  30420. if (this._scene) {
  30421. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30422. }
  30423. },
  30424. enumerable: true,
  30425. configurable: true
  30426. });
  30427. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30428. /**
  30429. * Gets whether or not the texture contains RGBD data.
  30430. */
  30431. get: function () {
  30432. return this._texture != null && this._texture._isRGBD;
  30433. },
  30434. enumerable: true,
  30435. configurable: true
  30436. });
  30437. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30438. get: function () {
  30439. if (this._texture)
  30440. return this._texture._lodGenerationOffset;
  30441. return 0.0;
  30442. },
  30443. set: function (value) {
  30444. if (this._texture)
  30445. this._texture._lodGenerationOffset = value;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30451. get: function () {
  30452. if (this._texture)
  30453. return this._texture._lodGenerationScale;
  30454. return 0.0;
  30455. },
  30456. set: function (value) {
  30457. if (this._texture)
  30458. this._texture._lodGenerationScale = value;
  30459. },
  30460. enumerable: true,
  30461. configurable: true
  30462. });
  30463. Object.defineProperty(BaseTexture.prototype, "uid", {
  30464. get: function () {
  30465. if (!this._uid) {
  30466. this._uid = BABYLON.Tools.RandomId();
  30467. }
  30468. return this._uid;
  30469. },
  30470. enumerable: true,
  30471. configurable: true
  30472. });
  30473. BaseTexture.prototype.toString = function () {
  30474. return this.name;
  30475. };
  30476. BaseTexture.prototype.getClassName = function () {
  30477. return "BaseTexture";
  30478. };
  30479. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30480. set: function (callback) {
  30481. if (this._onDisposeObserver) {
  30482. this.onDisposeObservable.remove(this._onDisposeObserver);
  30483. }
  30484. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30485. },
  30486. enumerable: true,
  30487. configurable: true
  30488. });
  30489. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30490. get: function () {
  30491. return true;
  30492. },
  30493. enumerable: true,
  30494. configurable: true
  30495. });
  30496. BaseTexture.prototype.getScene = function () {
  30497. return this._scene;
  30498. };
  30499. BaseTexture.prototype.getTextureMatrix = function () {
  30500. return BABYLON.Matrix.IdentityReadOnly;
  30501. };
  30502. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30503. return BABYLON.Matrix.IdentityReadOnly;
  30504. };
  30505. BaseTexture.prototype.getInternalTexture = function () {
  30506. return this._texture;
  30507. };
  30508. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30509. return !this.isBlocking || this.isReady();
  30510. };
  30511. BaseTexture.prototype.isReady = function () {
  30512. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30513. this.delayLoad();
  30514. return false;
  30515. }
  30516. if (this._texture) {
  30517. return this._texture.isReady;
  30518. }
  30519. return false;
  30520. };
  30521. BaseTexture.prototype.getSize = function () {
  30522. if (this._texture && this._texture.width) {
  30523. return new BABYLON.Size(this._texture.width, this._texture.height);
  30524. }
  30525. if (this._texture && this._texture._size) {
  30526. return new BABYLON.Size(this._texture._size, this._texture._size);
  30527. }
  30528. return BABYLON.Size.Zero();
  30529. };
  30530. BaseTexture.prototype.getBaseSize = function () {
  30531. if (!this.isReady() || !this._texture)
  30532. return BABYLON.Size.Zero();
  30533. if (this._texture._size) {
  30534. return new BABYLON.Size(this._texture._size, this._texture._size);
  30535. }
  30536. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30537. };
  30538. BaseTexture.prototype.scale = function (ratio) {
  30539. };
  30540. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30541. get: function () {
  30542. return false;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30548. if (!this._scene) {
  30549. return null;
  30550. }
  30551. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30552. for (var index = 0; index < texturesCache.length; index++) {
  30553. var texturesCacheEntry = texturesCache[index];
  30554. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30555. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30556. texturesCacheEntry.incrementReferences();
  30557. return texturesCacheEntry;
  30558. }
  30559. }
  30560. }
  30561. return null;
  30562. };
  30563. BaseTexture.prototype._rebuild = function () {
  30564. };
  30565. BaseTexture.prototype.delayLoad = function () {
  30566. };
  30567. BaseTexture.prototype.clone = function () {
  30568. return null;
  30569. };
  30570. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30571. get: function () {
  30572. if (!this._texture) {
  30573. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30574. }
  30575. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30581. get: function () {
  30582. if (!this._texture) {
  30583. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30584. }
  30585. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30586. },
  30587. enumerable: true,
  30588. configurable: true
  30589. });
  30590. /**
  30591. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30592. * This will returns an RGBA array buffer containing either in values (0-255) or
  30593. * float values (0-1) depending of the underlying buffer type.
  30594. * @param faceIndex The face of the texture to read (in case of cube texture)
  30595. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30596. * @returns The Array buffer containing the pixels data.
  30597. */
  30598. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30599. if (faceIndex === void 0) { faceIndex = 0; }
  30600. if (level === void 0) { level = 0; }
  30601. if (!this._texture) {
  30602. return null;
  30603. }
  30604. var size = this.getSize();
  30605. var width = size.width;
  30606. var height = size.height;
  30607. var scene = this.getScene();
  30608. if (!scene) {
  30609. return null;
  30610. }
  30611. var engine = scene.getEngine();
  30612. if (level != 0) {
  30613. width = width / Math.pow(2, level);
  30614. height = height / Math.pow(2, level);
  30615. width = Math.round(width);
  30616. height = Math.round(height);
  30617. }
  30618. if (this._texture.isCube) {
  30619. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30620. }
  30621. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30622. };
  30623. BaseTexture.prototype.releaseInternalTexture = function () {
  30624. if (this._texture) {
  30625. this._texture.dispose();
  30626. this._texture = null;
  30627. }
  30628. };
  30629. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30630. get: function () {
  30631. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30632. return null;
  30633. }
  30634. if (!this._texture._sphericalPolynomial) {
  30635. this._texture._sphericalPolynomial =
  30636. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30637. }
  30638. return this._texture._sphericalPolynomial;
  30639. },
  30640. set: function (value) {
  30641. if (this._texture) {
  30642. this._texture._sphericalPolynomial = value;
  30643. }
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30649. get: function () {
  30650. if (this._texture) {
  30651. return this._texture._lodTextureHigh;
  30652. }
  30653. return null;
  30654. },
  30655. enumerable: true,
  30656. configurable: true
  30657. });
  30658. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30659. get: function () {
  30660. if (this._texture) {
  30661. return this._texture._lodTextureMid;
  30662. }
  30663. return null;
  30664. },
  30665. enumerable: true,
  30666. configurable: true
  30667. });
  30668. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30669. get: function () {
  30670. if (this._texture) {
  30671. return this._texture._lodTextureLow;
  30672. }
  30673. return null;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. BaseTexture.prototype.dispose = function () {
  30679. if (!this._scene) {
  30680. return;
  30681. }
  30682. // Animations
  30683. this._scene.stopAnimation(this);
  30684. // Remove from scene
  30685. this._scene._removePendingData(this);
  30686. var index = this._scene.textures.indexOf(this);
  30687. if (index >= 0) {
  30688. this._scene.textures.splice(index, 1);
  30689. }
  30690. if (this._texture === undefined) {
  30691. return;
  30692. }
  30693. // Release
  30694. this.releaseInternalTexture();
  30695. // Callback
  30696. this.onDisposeObservable.notifyObservers(this);
  30697. this.onDisposeObservable.clear();
  30698. };
  30699. BaseTexture.prototype.serialize = function () {
  30700. if (!this.name) {
  30701. return null;
  30702. }
  30703. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30704. // Animations
  30705. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30706. return serializationObject;
  30707. };
  30708. BaseTexture.WhenAllReady = function (textures, callback) {
  30709. var numRemaining = textures.length;
  30710. if (numRemaining === 0) {
  30711. callback();
  30712. return;
  30713. }
  30714. var _loop_1 = function () {
  30715. texture = textures[i];
  30716. if (texture.isReady()) {
  30717. if (--numRemaining === 0) {
  30718. callback();
  30719. }
  30720. }
  30721. else {
  30722. onLoadObservable = texture.onLoadObservable;
  30723. var onLoadCallback_1 = function () {
  30724. onLoadObservable.removeCallback(onLoadCallback_1);
  30725. if (--numRemaining === 0) {
  30726. callback();
  30727. }
  30728. };
  30729. onLoadObservable.add(onLoadCallback_1);
  30730. }
  30731. };
  30732. var texture, onLoadObservable;
  30733. for (var i = 0; i < textures.length; i++) {
  30734. _loop_1();
  30735. }
  30736. };
  30737. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], BaseTexture.prototype, "name", void 0);
  30741. __decorate([
  30742. BABYLON.serialize("hasAlpha")
  30743. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], BaseTexture.prototype, "level", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30753. __decorate([
  30754. BABYLON.serialize("coordinatesMode")
  30755. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], BaseTexture.prototype, "wrapU", void 0);
  30759. __decorate([
  30760. BABYLON.serialize()
  30761. ], BaseTexture.prototype, "wrapV", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], BaseTexture.prototype, "wrapR", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], BaseTexture.prototype, "isCube", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], BaseTexture.prototype, "is3D", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], BaseTexture.prototype, "gammaSpace", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], BaseTexture.prototype, "invertZ", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], BaseTexture.prototype, "lodGenerationScale", null);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30792. return BaseTexture;
  30793. }());
  30794. BABYLON.BaseTexture = BaseTexture;
  30795. })(BABYLON || (BABYLON = {}));
  30796. //# sourceMappingURL=babylon.baseTexture.js.map
  30797. var BABYLON;
  30798. (function (BABYLON) {
  30799. var Texture = /** @class */ (function (_super) {
  30800. __extends(Texture, _super);
  30801. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30802. if (noMipmap === void 0) { noMipmap = false; }
  30803. if (invertY === void 0) { invertY = true; }
  30804. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30805. if (onLoad === void 0) { onLoad = null; }
  30806. if (onError === void 0) { onError = null; }
  30807. if (buffer === void 0) { buffer = null; }
  30808. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30809. var _this = _super.call(this, scene) || this;
  30810. _this.uOffset = 0;
  30811. _this.vOffset = 0;
  30812. _this.uScale = 1.0;
  30813. _this.vScale = 1.0;
  30814. _this.uAng = 0;
  30815. _this.vAng = 0;
  30816. _this.wAng = 0;
  30817. /**
  30818. * Defines the center of rotation (U)
  30819. */
  30820. _this.uRotationCenter = 0.5;
  30821. /**
  30822. * Defines the center of rotation (V)
  30823. */
  30824. _this.vRotationCenter = 0.5;
  30825. /**
  30826. * Defines the center of rotation (W)
  30827. */
  30828. _this.wRotationCenter = 0.5;
  30829. _this._isBlocking = true;
  30830. _this.name = url || "";
  30831. _this.url = url;
  30832. _this._noMipmap = noMipmap;
  30833. _this._invertY = invertY;
  30834. _this._samplingMode = samplingMode;
  30835. _this._buffer = buffer;
  30836. _this._deleteBuffer = deleteBuffer;
  30837. if (format) {
  30838. _this._format = format;
  30839. }
  30840. scene = _this.getScene();
  30841. if (!scene) {
  30842. return _this;
  30843. }
  30844. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30845. var load = function () {
  30846. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30847. _this.onLoadObservable.notifyObservers(_this);
  30848. }
  30849. if (onLoad) {
  30850. onLoad();
  30851. }
  30852. if (!_this.isBlocking && scene) {
  30853. scene.resetCachedMaterial();
  30854. }
  30855. };
  30856. if (!_this.url) {
  30857. _this._delayedOnLoad = load;
  30858. _this._delayedOnError = onError;
  30859. return _this;
  30860. }
  30861. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30862. if (!_this._texture) {
  30863. if (!scene.useDelayedTextureLoading) {
  30864. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30865. if (deleteBuffer) {
  30866. delete _this._buffer;
  30867. }
  30868. }
  30869. else {
  30870. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30871. _this._delayedOnLoad = load;
  30872. _this._delayedOnError = onError;
  30873. }
  30874. }
  30875. else {
  30876. if (_this._texture.isReady) {
  30877. BABYLON.Tools.SetImmediate(function () { return load(); });
  30878. }
  30879. else {
  30880. _this._texture.onLoadedObservable.add(load);
  30881. }
  30882. }
  30883. return _this;
  30884. }
  30885. Object.defineProperty(Texture.prototype, "noMipmap", {
  30886. get: function () {
  30887. return this._noMipmap;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. Object.defineProperty(Texture.prototype, "isBlocking", {
  30893. get: function () {
  30894. return this._isBlocking;
  30895. },
  30896. set: function (value) {
  30897. this._isBlocking = value;
  30898. },
  30899. enumerable: true,
  30900. configurable: true
  30901. });
  30902. Object.defineProperty(Texture.prototype, "samplingMode", {
  30903. get: function () {
  30904. return this._samplingMode;
  30905. },
  30906. enumerable: true,
  30907. configurable: true
  30908. });
  30909. /**
  30910. * Update the url (and optional buffer) of this texture if url was null during construction.
  30911. * @param url the url of the texture
  30912. * @param buffer the buffer of the texture (defaults to null)
  30913. */
  30914. Texture.prototype.updateURL = function (url, buffer) {
  30915. if (buffer === void 0) { buffer = null; }
  30916. if (this.url) {
  30917. throw new Error("URL is already set");
  30918. }
  30919. this.url = url;
  30920. this._buffer = buffer;
  30921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30922. this.delayLoad();
  30923. };
  30924. Texture.prototype.delayLoad = function () {
  30925. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30926. return;
  30927. }
  30928. var scene = this.getScene();
  30929. if (!scene) {
  30930. return;
  30931. }
  30932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30933. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30934. if (!this._texture) {
  30935. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30936. if (this._deleteBuffer) {
  30937. delete this._buffer;
  30938. }
  30939. }
  30940. else {
  30941. if (this._delayedOnLoad) {
  30942. if (this._texture.isReady) {
  30943. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30944. }
  30945. else {
  30946. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30947. }
  30948. }
  30949. }
  30950. this._delayedOnLoad = null;
  30951. this._delayedOnError = null;
  30952. };
  30953. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30954. if (!this._texture) {
  30955. return;
  30956. }
  30957. var scene = this.getScene();
  30958. if (!scene) {
  30959. return;
  30960. }
  30961. this._samplingMode = samplingMode;
  30962. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30963. };
  30964. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30965. x *= this.uScale;
  30966. y *= this.vScale;
  30967. x -= this.uRotationCenter * this.uScale;
  30968. y -= this.vRotationCenter * this.vScale;
  30969. z -= this.wRotationCenter;
  30970. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30971. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30972. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30973. t.z += this.wRotationCenter;
  30974. };
  30975. Texture.prototype.getTextureMatrix = function () {
  30976. var _this = this;
  30977. if (this.uOffset === this._cachedUOffset &&
  30978. this.vOffset === this._cachedVOffset &&
  30979. this.uScale === this._cachedUScale &&
  30980. this.vScale === this._cachedVScale &&
  30981. this.uAng === this._cachedUAng &&
  30982. this.vAng === this._cachedVAng &&
  30983. this.wAng === this._cachedWAng) {
  30984. return this._cachedTextureMatrix;
  30985. }
  30986. this._cachedUOffset = this.uOffset;
  30987. this._cachedVOffset = this.vOffset;
  30988. this._cachedUScale = this.uScale;
  30989. this._cachedVScale = this.vScale;
  30990. this._cachedUAng = this.uAng;
  30991. this._cachedVAng = this.vAng;
  30992. this._cachedWAng = this.wAng;
  30993. if (!this._cachedTextureMatrix) {
  30994. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30995. this._rowGenerationMatrix = new BABYLON.Matrix();
  30996. this._t0 = BABYLON.Vector3.Zero();
  30997. this._t1 = BABYLON.Vector3.Zero();
  30998. this._t2 = BABYLON.Vector3.Zero();
  30999. }
  31000. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31001. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31002. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31003. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31004. this._t1.subtractInPlace(this._t0);
  31005. this._t2.subtractInPlace(this._t0);
  31006. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31007. this._cachedTextureMatrix.m[0] = this._t1.x;
  31008. this._cachedTextureMatrix.m[1] = this._t1.y;
  31009. this._cachedTextureMatrix.m[2] = this._t1.z;
  31010. this._cachedTextureMatrix.m[4] = this._t2.x;
  31011. this._cachedTextureMatrix.m[5] = this._t2.y;
  31012. this._cachedTextureMatrix.m[6] = this._t2.z;
  31013. this._cachedTextureMatrix.m[8] = this._t0.x;
  31014. this._cachedTextureMatrix.m[9] = this._t0.y;
  31015. this._cachedTextureMatrix.m[10] = this._t0.z;
  31016. var scene = this.getScene();
  31017. if (!scene) {
  31018. return this._cachedTextureMatrix;
  31019. }
  31020. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31021. return mat.hasTexture(_this);
  31022. });
  31023. return this._cachedTextureMatrix;
  31024. };
  31025. Texture.prototype.getReflectionTextureMatrix = function () {
  31026. var _this = this;
  31027. var scene = this.getScene();
  31028. if (!scene) {
  31029. return this._cachedTextureMatrix;
  31030. }
  31031. if (this.uOffset === this._cachedUOffset &&
  31032. this.vOffset === this._cachedVOffset &&
  31033. this.uScale === this._cachedUScale &&
  31034. this.vScale === this._cachedVScale &&
  31035. this.coordinatesMode === this._cachedCoordinatesMode) {
  31036. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31037. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31038. return this._cachedTextureMatrix;
  31039. }
  31040. }
  31041. else {
  31042. return this._cachedTextureMatrix;
  31043. }
  31044. }
  31045. if (!this._cachedTextureMatrix) {
  31046. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31047. }
  31048. if (!this._projectionModeMatrix) {
  31049. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31050. }
  31051. this._cachedUOffset = this.uOffset;
  31052. this._cachedVOffset = this.vOffset;
  31053. this._cachedUScale = this.uScale;
  31054. this._cachedVScale = this.vScale;
  31055. this._cachedCoordinatesMode = this.coordinatesMode;
  31056. switch (this.coordinatesMode) {
  31057. case Texture.PLANAR_MODE:
  31058. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31059. this._cachedTextureMatrix[0] = this.uScale;
  31060. this._cachedTextureMatrix[5] = this.vScale;
  31061. this._cachedTextureMatrix[12] = this.uOffset;
  31062. this._cachedTextureMatrix[13] = this.vOffset;
  31063. break;
  31064. case Texture.PROJECTION_MODE:
  31065. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31066. this._projectionModeMatrix.m[0] = 0.5;
  31067. this._projectionModeMatrix.m[5] = -0.5;
  31068. this._projectionModeMatrix.m[10] = 0.0;
  31069. this._projectionModeMatrix.m[12] = 0.5;
  31070. this._projectionModeMatrix.m[13] = 0.5;
  31071. this._projectionModeMatrix.m[14] = 1.0;
  31072. this._projectionModeMatrix.m[15] = 1.0;
  31073. var projectionMatrix = scene.getProjectionMatrix();
  31074. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31075. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31076. break;
  31077. default:
  31078. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31079. break;
  31080. }
  31081. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31082. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31083. });
  31084. return this._cachedTextureMatrix;
  31085. };
  31086. Texture.prototype.clone = function () {
  31087. var _this = this;
  31088. return BABYLON.SerializationHelper.Clone(function () {
  31089. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31090. }, this);
  31091. };
  31092. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31093. get: function () {
  31094. if (!this._onLoadObservable) {
  31095. this._onLoadObservable = new BABYLON.Observable();
  31096. }
  31097. return this._onLoadObservable;
  31098. },
  31099. enumerable: true,
  31100. configurable: true
  31101. });
  31102. Texture.prototype.serialize = function () {
  31103. var serializationObject = _super.prototype.serialize.call(this);
  31104. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31105. serializationObject.base64String = this._buffer;
  31106. serializationObject.name = serializationObject.name.replace("data:", "");
  31107. }
  31108. serializationObject.invertY = this._invertY;
  31109. serializationObject.samplingMode = this.samplingMode;
  31110. return serializationObject;
  31111. };
  31112. Texture.prototype.getClassName = function () {
  31113. return "Texture";
  31114. };
  31115. Texture.prototype.dispose = function () {
  31116. _super.prototype.dispose.call(this);
  31117. if (this.onLoadObservable) {
  31118. this.onLoadObservable.clear();
  31119. this._onLoadObservable = null;
  31120. }
  31121. this._delayedOnLoad = null;
  31122. this._delayedOnError = null;
  31123. };
  31124. // Statics
  31125. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31126. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31127. if (onLoad === void 0) { onLoad = null; }
  31128. if (onError === void 0) { onError = null; }
  31129. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31130. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31131. };
  31132. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31133. if (parsedTexture.customType) {
  31134. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31135. // Update Sampling Mode
  31136. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31137. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31138. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31139. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31140. }
  31141. }
  31142. return parsedCustomTexture;
  31143. }
  31144. if (parsedTexture.isCube) {
  31145. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31146. }
  31147. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31148. return null;
  31149. }
  31150. var texture = BABYLON.SerializationHelper.Parse(function () {
  31151. var generateMipMaps = true;
  31152. if (parsedTexture.noMipmap) {
  31153. generateMipMaps = false;
  31154. }
  31155. if (parsedTexture.mirrorPlane) {
  31156. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31157. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31158. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31159. return mirrorTexture;
  31160. }
  31161. else if (parsedTexture.isRenderTarget) {
  31162. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31163. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31164. return renderTargetTexture;
  31165. }
  31166. else {
  31167. var texture;
  31168. if (parsedTexture.base64String) {
  31169. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31170. }
  31171. else {
  31172. var url = rootUrl + parsedTexture.name;
  31173. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31174. url = parsedTexture.url;
  31175. }
  31176. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31177. }
  31178. return texture;
  31179. }
  31180. }, parsedTexture, scene);
  31181. // Update Sampling Mode
  31182. if (parsedTexture.samplingMode) {
  31183. var sampling = parsedTexture.samplingMode;
  31184. if (texture._samplingMode !== sampling) {
  31185. texture.updateSamplingMode(sampling);
  31186. }
  31187. }
  31188. // Animations
  31189. if (parsedTexture.animations) {
  31190. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31191. var parsedAnimation = parsedTexture.animations[animationIndex];
  31192. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31193. }
  31194. }
  31195. return texture;
  31196. };
  31197. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31198. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31199. if (noMipmap === void 0) { noMipmap = false; }
  31200. if (invertY === void 0) { invertY = true; }
  31201. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31202. if (onLoad === void 0) { onLoad = null; }
  31203. if (onError === void 0) { onError = null; }
  31204. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31205. if (name.substr(0, 5) !== "data:") {
  31206. name = "data:" + name;
  31207. }
  31208. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31209. };
  31210. // Constants
  31211. Texture.NEAREST_SAMPLINGMODE = 1;
  31212. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31213. Texture.BILINEAR_SAMPLINGMODE = 2;
  31214. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31215. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31216. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31217. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31218. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31219. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31220. Texture.NEAREST_LINEAR = 7;
  31221. Texture.NEAREST_NEAREST = 8;
  31222. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31223. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31224. Texture.LINEAR_LINEAR = 11;
  31225. Texture.LINEAR_NEAREST = 12;
  31226. Texture.EXPLICIT_MODE = 0;
  31227. Texture.SPHERICAL_MODE = 1;
  31228. Texture.PLANAR_MODE = 2;
  31229. Texture.CUBIC_MODE = 3;
  31230. Texture.PROJECTION_MODE = 4;
  31231. Texture.SKYBOX_MODE = 5;
  31232. Texture.INVCUBIC_MODE = 6;
  31233. Texture.EQUIRECTANGULAR_MODE = 7;
  31234. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31235. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31236. Texture.CLAMP_ADDRESSMODE = 0;
  31237. Texture.WRAP_ADDRESSMODE = 1;
  31238. Texture.MIRROR_ADDRESSMODE = 2;
  31239. /**
  31240. * 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
  31241. */
  31242. Texture.UseSerializedUrlIfAny = false;
  31243. __decorate([
  31244. BABYLON.serialize()
  31245. ], Texture.prototype, "url", void 0);
  31246. __decorate([
  31247. BABYLON.serialize()
  31248. ], Texture.prototype, "uOffset", void 0);
  31249. __decorate([
  31250. BABYLON.serialize()
  31251. ], Texture.prototype, "vOffset", void 0);
  31252. __decorate([
  31253. BABYLON.serialize()
  31254. ], Texture.prototype, "uScale", void 0);
  31255. __decorate([
  31256. BABYLON.serialize()
  31257. ], Texture.prototype, "vScale", void 0);
  31258. __decorate([
  31259. BABYLON.serialize()
  31260. ], Texture.prototype, "uAng", void 0);
  31261. __decorate([
  31262. BABYLON.serialize()
  31263. ], Texture.prototype, "vAng", void 0);
  31264. __decorate([
  31265. BABYLON.serialize()
  31266. ], Texture.prototype, "wAng", void 0);
  31267. __decorate([
  31268. BABYLON.serialize()
  31269. ], Texture.prototype, "uRotationCenter", void 0);
  31270. __decorate([
  31271. BABYLON.serialize()
  31272. ], Texture.prototype, "vRotationCenter", void 0);
  31273. __decorate([
  31274. BABYLON.serialize()
  31275. ], Texture.prototype, "wRotationCenter", void 0);
  31276. __decorate([
  31277. BABYLON.serialize()
  31278. ], Texture.prototype, "isBlocking", null);
  31279. return Texture;
  31280. }(BABYLON.BaseTexture));
  31281. BABYLON.Texture = Texture;
  31282. })(BABYLON || (BABYLON = {}));
  31283. //# sourceMappingURL=babylon.texture.js.map
  31284. var BABYLON;
  31285. (function (BABYLON) {
  31286. /**
  31287. * @hidden
  31288. **/
  31289. var _InstancesBatch = /** @class */ (function () {
  31290. function _InstancesBatch() {
  31291. this.mustReturn = false;
  31292. this.visibleInstances = new Array();
  31293. this.renderSelf = new Array();
  31294. }
  31295. return _InstancesBatch;
  31296. }());
  31297. BABYLON._InstancesBatch = _InstancesBatch;
  31298. var Mesh = /** @class */ (function (_super) {
  31299. __extends(Mesh, _super);
  31300. /**
  31301. * @constructor
  31302. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31303. * @param {Scene} scene The scene to add this mesh to.
  31304. * @param {Node} parent The parent of this mesh, if it has one
  31305. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31306. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31307. * When false, achieved by calling a clone(), also passing False.
  31308. * This will make creation of children, recursive.
  31309. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31310. */
  31311. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31312. if (scene === void 0) { scene = null; }
  31313. if (parent === void 0) { parent = null; }
  31314. if (source === void 0) { source = null; }
  31315. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31316. var _this = _super.call(this, name, scene) || this;
  31317. // Events
  31318. /**
  31319. * An event triggered before rendering the mesh
  31320. */
  31321. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31322. /**
  31323. * An event triggered after rendering the mesh
  31324. */
  31325. _this.onAfterRenderObservable = new BABYLON.Observable();
  31326. /**
  31327. * An event triggered before drawing the mesh
  31328. */
  31329. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31330. // Members
  31331. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31332. _this.instances = new Array();
  31333. _this._LODLevels = new Array();
  31334. _this._visibleInstances = {};
  31335. _this._renderIdForInstances = new Array();
  31336. _this._batchCache = new _InstancesBatch();
  31337. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31338. // Use by builder only to know what orientation were the mesh build in.
  31339. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31340. _this.overrideMaterialSideOrientation = null;
  31341. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31342. // Will be used to save a source mesh reference, If any
  31343. _this._source = null;
  31344. scene = _this.getScene();
  31345. if (source) {
  31346. // Geometry
  31347. if (source._geometry) {
  31348. source._geometry.applyToMesh(_this);
  31349. }
  31350. // Deep copy
  31351. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31352. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31353. // Source mesh
  31354. _this._source = source;
  31355. // Metadata
  31356. if (source.metadata && source.metadata.clone) {
  31357. _this.metadata = source.metadata.clone();
  31358. }
  31359. else {
  31360. _this.metadata = source.metadata;
  31361. }
  31362. // Tags
  31363. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31364. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31365. }
  31366. // Parent
  31367. _this.parent = source.parent;
  31368. // Pivot
  31369. _this.setPivotMatrix(source.getPivotMatrix());
  31370. _this.id = name + "." + source.id;
  31371. // Material
  31372. _this.material = source.material;
  31373. var index;
  31374. if (!doNotCloneChildren) {
  31375. // Children
  31376. var directDescendants = source.getDescendants(true);
  31377. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31378. var child = directDescendants[index_1];
  31379. if (child.clone) {
  31380. child.clone(name + "." + child.name, _this);
  31381. }
  31382. }
  31383. }
  31384. // Physics clone
  31385. var physicsEngine = _this.getScene().getPhysicsEngine();
  31386. if (clonePhysicsImpostor && physicsEngine) {
  31387. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31388. if (impostor) {
  31389. _this.physicsImpostor = impostor.clone(_this);
  31390. }
  31391. }
  31392. // Particles
  31393. for (index = 0; index < scene.particleSystems.length; index++) {
  31394. var system = scene.particleSystems[index];
  31395. if (system.emitter === source) {
  31396. system.clone(system.name, _this);
  31397. }
  31398. }
  31399. _this.computeWorldMatrix(true);
  31400. }
  31401. // Parent
  31402. if (parent !== null) {
  31403. _this.parent = parent;
  31404. }
  31405. return _this;
  31406. }
  31407. Object.defineProperty(Mesh, "FRONTSIDE", {
  31408. /**
  31409. * Mesh side orientation : usually the external or front surface
  31410. */
  31411. get: function () {
  31412. return Mesh._FRONTSIDE;
  31413. },
  31414. enumerable: true,
  31415. configurable: true
  31416. });
  31417. Object.defineProperty(Mesh, "BACKSIDE", {
  31418. /**
  31419. * Mesh side orientation : usually the internal or back surface
  31420. */
  31421. get: function () {
  31422. return Mesh._BACKSIDE;
  31423. },
  31424. enumerable: true,
  31425. configurable: true
  31426. });
  31427. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31428. /**
  31429. * Mesh side orientation : both internal and external or front and back surfaces
  31430. */
  31431. get: function () {
  31432. return Mesh._DOUBLESIDE;
  31433. },
  31434. enumerable: true,
  31435. configurable: true
  31436. });
  31437. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31438. /**
  31439. * Mesh side orientation : by default, `FRONTSIDE`
  31440. */
  31441. get: function () {
  31442. return Mesh._DEFAULTSIDE;
  31443. },
  31444. enumerable: true,
  31445. configurable: true
  31446. });
  31447. Object.defineProperty(Mesh, "NO_CAP", {
  31448. /**
  31449. * Mesh cap setting : no cap
  31450. */
  31451. get: function () {
  31452. return Mesh._NO_CAP;
  31453. },
  31454. enumerable: true,
  31455. configurable: true
  31456. });
  31457. Object.defineProperty(Mesh, "CAP_START", {
  31458. /**
  31459. * Mesh cap setting : one cap at the beginning of the mesh
  31460. */
  31461. get: function () {
  31462. return Mesh._CAP_START;
  31463. },
  31464. enumerable: true,
  31465. configurable: true
  31466. });
  31467. Object.defineProperty(Mesh, "CAP_END", {
  31468. /**
  31469. * Mesh cap setting : one cap at the end of the mesh
  31470. */
  31471. get: function () {
  31472. return Mesh._CAP_END;
  31473. },
  31474. enumerable: true,
  31475. configurable: true
  31476. });
  31477. Object.defineProperty(Mesh, "CAP_ALL", {
  31478. /**
  31479. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31480. */
  31481. get: function () {
  31482. return Mesh._CAP_ALL;
  31483. },
  31484. enumerable: true,
  31485. configurable: true
  31486. });
  31487. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31488. set: function (callback) {
  31489. if (this._onBeforeDrawObserver) {
  31490. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31491. }
  31492. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31493. },
  31494. enumerable: true,
  31495. configurable: true
  31496. });
  31497. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31498. get: function () {
  31499. return this._morphTargetManager;
  31500. },
  31501. set: function (value) {
  31502. if (this._morphTargetManager === value) {
  31503. return;
  31504. }
  31505. this._morphTargetManager = value;
  31506. this._syncGeometryWithMorphTargetManager();
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(Mesh.prototype, "source", {
  31512. get: function () {
  31513. return this._source;
  31514. },
  31515. enumerable: true,
  31516. configurable: true
  31517. });
  31518. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31519. get: function () {
  31520. return this._unIndexed;
  31521. },
  31522. set: function (value) {
  31523. if (this._unIndexed !== value) {
  31524. this._unIndexed = value;
  31525. this._markSubMeshesAsAttributesDirty();
  31526. }
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. // Methods
  31532. /**
  31533. * Returns the string "Mesh".
  31534. */
  31535. Mesh.prototype.getClassName = function () {
  31536. return "Mesh";
  31537. };
  31538. /**
  31539. * Returns a string.
  31540. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31541. */
  31542. Mesh.prototype.toString = function (fullDetails) {
  31543. var ret = _super.prototype.toString.call(this, fullDetails);
  31544. ret += ", n vertices: " + this.getTotalVertices();
  31545. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31546. if (this.animations) {
  31547. for (var i = 0; i < this.animations.length; i++) {
  31548. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31549. }
  31550. }
  31551. if (fullDetails) {
  31552. if (this._geometry) {
  31553. var ib = this.getIndices();
  31554. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31555. if (vb && ib) {
  31556. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31557. }
  31558. }
  31559. else {
  31560. ret += ", flat shading: UNKNOWN";
  31561. }
  31562. }
  31563. return ret;
  31564. };
  31565. Mesh.prototype._unBindEffect = function () {
  31566. _super.prototype._unBindEffect.call(this);
  31567. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31568. var instance = _a[_i];
  31569. instance._unBindEffect();
  31570. }
  31571. };
  31572. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31573. /**
  31574. * True if the mesh has some Levels Of Details (LOD).
  31575. * Returns a boolean.
  31576. */
  31577. get: function () {
  31578. return this._LODLevels.length > 0;
  31579. },
  31580. enumerable: true,
  31581. configurable: true
  31582. });
  31583. /**
  31584. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31585. * @returns an array of {BABYLON.MeshLODLevel}
  31586. */
  31587. Mesh.prototype.getLODLevels = function () {
  31588. return this._LODLevels;
  31589. };
  31590. Mesh.prototype._sortLODLevels = function () {
  31591. this._LODLevels.sort(function (a, b) {
  31592. if (a.distance < b.distance) {
  31593. return 1;
  31594. }
  31595. if (a.distance > b.distance) {
  31596. return -1;
  31597. }
  31598. return 0;
  31599. });
  31600. };
  31601. /**
  31602. * Add a mesh as LOD level triggered at the given distance.
  31603. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31604. * @param distance The distance from the center of the object to show this level
  31605. * @param mesh The mesh to be added as LOD level (can be null)
  31606. * @return This mesh (for chaining)
  31607. */
  31608. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31609. if (mesh && mesh._masterMesh) {
  31610. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31611. return this;
  31612. }
  31613. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31614. this._LODLevels.push(level);
  31615. if (mesh) {
  31616. mesh._masterMesh = this;
  31617. }
  31618. this._sortLODLevels();
  31619. return this;
  31620. };
  31621. /**
  31622. * Returns the LOD level mesh at the passed distance or null if not found.
  31623. * It is related to the method `addLODLevel(distance, mesh)`.
  31624. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31625. * Returns an object Mesh or `null`.
  31626. */
  31627. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31628. for (var index = 0; index < this._LODLevels.length; index++) {
  31629. var level = this._LODLevels[index];
  31630. if (level.distance === distance) {
  31631. return level.mesh;
  31632. }
  31633. }
  31634. return null;
  31635. };
  31636. /**
  31637. * Remove a mesh from the LOD array
  31638. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31639. * @param {Mesh} mesh The mesh to be removed.
  31640. * @return {Mesh} This mesh (for chaining)
  31641. */
  31642. Mesh.prototype.removeLODLevel = function (mesh) {
  31643. for (var index = 0; index < this._LODLevels.length; index++) {
  31644. if (this._LODLevels[index].mesh === mesh) {
  31645. this._LODLevels.splice(index, 1);
  31646. if (mesh) {
  31647. mesh._masterMesh = null;
  31648. }
  31649. }
  31650. }
  31651. this._sortLODLevels();
  31652. return this;
  31653. };
  31654. /**
  31655. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31656. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31657. */
  31658. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31659. if (!this._LODLevels || this._LODLevels.length === 0) {
  31660. return this;
  31661. }
  31662. var bSphere;
  31663. if (boundingSphere) {
  31664. bSphere = boundingSphere;
  31665. }
  31666. else {
  31667. var boundingInfo = this.getBoundingInfo();
  31668. bSphere = boundingInfo.boundingSphere;
  31669. }
  31670. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31671. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31672. if (this.onLODLevelSelection) {
  31673. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31674. }
  31675. return this;
  31676. }
  31677. for (var index = 0; index < this._LODLevels.length; index++) {
  31678. var level = this._LODLevels[index];
  31679. if (level.distance < distanceToCamera) {
  31680. if (level.mesh) {
  31681. level.mesh._preActivate();
  31682. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31683. }
  31684. if (this.onLODLevelSelection) {
  31685. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31686. }
  31687. return level.mesh;
  31688. }
  31689. }
  31690. if (this.onLODLevelSelection) {
  31691. this.onLODLevelSelection(distanceToCamera, this, this);
  31692. }
  31693. return this;
  31694. };
  31695. Object.defineProperty(Mesh.prototype, "geometry", {
  31696. /**
  31697. * Returns the mesh internal Geometry object.
  31698. */
  31699. get: function () {
  31700. return this._geometry;
  31701. },
  31702. enumerable: true,
  31703. configurable: true
  31704. });
  31705. /**
  31706. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31707. */
  31708. Mesh.prototype.getTotalVertices = function () {
  31709. if (this._geometry === null || this._geometry === undefined) {
  31710. return 0;
  31711. }
  31712. return this._geometry.getTotalVertices();
  31713. };
  31714. /**
  31715. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31716. * 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.
  31717. * You can force the copy with forceCopy === true
  31718. * Returns null if the mesh has no geometry or no vertex buffer.
  31719. * Possible `kind` values :
  31720. * - BABYLON.VertexBuffer.PositionKind
  31721. * - BABYLON.VertexBuffer.UVKind
  31722. * - BABYLON.VertexBuffer.UV2Kind
  31723. * - BABYLON.VertexBuffer.UV3Kind
  31724. * - BABYLON.VertexBuffer.UV4Kind
  31725. * - BABYLON.VertexBuffer.UV5Kind
  31726. * - BABYLON.VertexBuffer.UV6Kind
  31727. * - BABYLON.VertexBuffer.ColorKind
  31728. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31729. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31730. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31731. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31732. */
  31733. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31734. if (!this._geometry) {
  31735. return null;
  31736. }
  31737. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31738. };
  31739. /**
  31740. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31741. * Returns `null` if the mesh has no geometry.
  31742. * Possible `kind` values :
  31743. * - BABYLON.VertexBuffer.PositionKind
  31744. * - BABYLON.VertexBuffer.UVKind
  31745. * - BABYLON.VertexBuffer.UV2Kind
  31746. * - BABYLON.VertexBuffer.UV3Kind
  31747. * - BABYLON.VertexBuffer.UV4Kind
  31748. * - BABYLON.VertexBuffer.UV5Kind
  31749. * - BABYLON.VertexBuffer.UV6Kind
  31750. * - BABYLON.VertexBuffer.ColorKind
  31751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31755. */
  31756. Mesh.prototype.getVertexBuffer = function (kind) {
  31757. if (!this._geometry) {
  31758. return null;
  31759. }
  31760. return this._geometry.getVertexBuffer(kind);
  31761. };
  31762. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31763. if (!this._geometry) {
  31764. if (this._delayInfo) {
  31765. return this._delayInfo.indexOf(kind) !== -1;
  31766. }
  31767. return false;
  31768. }
  31769. return this._geometry.isVerticesDataPresent(kind);
  31770. };
  31771. /**
  31772. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31773. * Possible `kind` values :
  31774. * - BABYLON.VertexBuffer.PositionKind
  31775. * - BABYLON.VertexBuffer.UVKind
  31776. * - BABYLON.VertexBuffer.UV2Kind
  31777. * - BABYLON.VertexBuffer.UV3Kind
  31778. * - BABYLON.VertexBuffer.UV4Kind
  31779. * - BABYLON.VertexBuffer.UV5Kind
  31780. * - BABYLON.VertexBuffer.UV6Kind
  31781. * - BABYLON.VertexBuffer.ColorKind
  31782. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31783. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31784. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31785. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31786. */
  31787. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31788. if (!this._geometry) {
  31789. if (this._delayInfo) {
  31790. return this._delayInfo.indexOf(kind) !== -1;
  31791. }
  31792. return false;
  31793. }
  31794. return this._geometry.isVertexBufferUpdatable(kind);
  31795. };
  31796. /**
  31797. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31798. * Possible `kind` values :
  31799. * - BABYLON.VertexBuffer.PositionKind
  31800. * - BABYLON.VertexBuffer.UVKind
  31801. * - BABYLON.VertexBuffer.UV2Kind
  31802. * - BABYLON.VertexBuffer.UV3Kind
  31803. * - BABYLON.VertexBuffer.UV4Kind
  31804. * - BABYLON.VertexBuffer.UV5Kind
  31805. * - BABYLON.VertexBuffer.UV6Kind
  31806. * - BABYLON.VertexBuffer.ColorKind
  31807. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31808. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31809. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31810. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31811. */
  31812. Mesh.prototype.getVerticesDataKinds = function () {
  31813. if (!this._geometry) {
  31814. var result = new Array();
  31815. if (this._delayInfo) {
  31816. this._delayInfo.forEach(function (kind, index, array) {
  31817. result.push(kind);
  31818. });
  31819. }
  31820. return result;
  31821. }
  31822. return this._geometry.getVerticesDataKinds();
  31823. };
  31824. /**
  31825. * Returns a positive integer : the total number of indices in this mesh geometry.
  31826. * Returns zero if the mesh has no geometry.
  31827. */
  31828. Mesh.prototype.getTotalIndices = function () {
  31829. if (!this._geometry) {
  31830. return 0;
  31831. }
  31832. return this._geometry.getTotalIndices();
  31833. };
  31834. /**
  31835. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31836. * 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.
  31837. * Returns an empty array if the mesh has no geometry.
  31838. */
  31839. Mesh.prototype.getIndices = function (copyWhenShared) {
  31840. if (!this._geometry) {
  31841. return [];
  31842. }
  31843. return this._geometry.getIndices(copyWhenShared);
  31844. };
  31845. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31846. get: function () {
  31847. return this._masterMesh !== null && this._masterMesh !== undefined;
  31848. },
  31849. enumerable: true,
  31850. configurable: true
  31851. });
  31852. /**
  31853. * Determine if the current mesh is ready to be rendered
  31854. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31855. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31856. * @returns true if all associated assets are ready (material, textures, shaders)
  31857. */
  31858. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31859. if (completeCheck === void 0) { completeCheck = false; }
  31860. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31861. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31862. return false;
  31863. }
  31864. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31865. return false;
  31866. }
  31867. if (!this.subMeshes || this.subMeshes.length === 0) {
  31868. return true;
  31869. }
  31870. if (!completeCheck) {
  31871. return true;
  31872. }
  31873. var engine = this.getEngine();
  31874. var scene = this.getScene();
  31875. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31876. this.computeWorldMatrix();
  31877. var mat = this.material || scene.defaultMaterial;
  31878. if (mat) {
  31879. if (mat.storeEffectOnSubMeshes) {
  31880. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31881. var subMesh = _a[_i];
  31882. var effectiveMaterial = subMesh.getMaterial();
  31883. if (effectiveMaterial) {
  31884. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31885. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31886. return false;
  31887. }
  31888. }
  31889. else {
  31890. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31891. return false;
  31892. }
  31893. }
  31894. }
  31895. }
  31896. }
  31897. else {
  31898. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31899. return false;
  31900. }
  31901. }
  31902. }
  31903. // Shadows
  31904. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31905. var light = _c[_b];
  31906. var generator = light.getShadowGenerator();
  31907. if (generator) {
  31908. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31909. var subMesh = _e[_d];
  31910. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31911. return false;
  31912. }
  31913. }
  31914. }
  31915. }
  31916. // LOD
  31917. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31918. var lod = _g[_f];
  31919. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31920. return false;
  31921. }
  31922. }
  31923. return true;
  31924. };
  31925. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31926. /**
  31927. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31928. * This property is pertinent only for updatable parametric shapes.
  31929. */
  31930. get: function () {
  31931. return this._areNormalsFrozen;
  31932. },
  31933. enumerable: true,
  31934. configurable: true
  31935. });
  31936. /**
  31937. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31938. * It has no effect at all on other shapes.
  31939. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31940. * Returns the Mesh.
  31941. */
  31942. Mesh.prototype.freezeNormals = function () {
  31943. this._areNormalsFrozen = true;
  31944. return this;
  31945. };
  31946. /**
  31947. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31948. * It has no effect at all on other shapes.
  31949. * It reactivates the mesh normals computation if it was previously frozen.
  31950. * Returns the Mesh.
  31951. */
  31952. Mesh.prototype.unfreezeNormals = function () {
  31953. this._areNormalsFrozen = false;
  31954. return this;
  31955. };
  31956. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31957. /**
  31958. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31959. */
  31960. set: function (count) {
  31961. this._overridenInstanceCount = count;
  31962. },
  31963. enumerable: true,
  31964. configurable: true
  31965. });
  31966. // Methods
  31967. Mesh.prototype._preActivate = function () {
  31968. var sceneRenderId = this.getScene().getRenderId();
  31969. if (this._preActivateId === sceneRenderId) {
  31970. return this;
  31971. }
  31972. this._preActivateId = sceneRenderId;
  31973. this._visibleInstances = null;
  31974. return this;
  31975. };
  31976. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31977. if (this._visibleInstances) {
  31978. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31979. }
  31980. return this;
  31981. };
  31982. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31983. if (!this._visibleInstances) {
  31984. this._visibleInstances = {};
  31985. this._visibleInstances.defaultRenderId = renderId;
  31986. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31987. }
  31988. if (!this._visibleInstances[renderId]) {
  31989. this._visibleInstances[renderId] = new Array();
  31990. }
  31991. this._visibleInstances[renderId].push(instance);
  31992. return this;
  31993. };
  31994. /**
  31995. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31996. * This means the mesh underlying bounding box and sphere are recomputed.
  31997. * Returns the Mesh.
  31998. */
  31999. Mesh.prototype.refreshBoundingInfo = function () {
  32000. return this._refreshBoundingInfo(false);
  32001. };
  32002. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32003. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32004. return this;
  32005. }
  32006. var data = this._getPositionData(applySkeleton);
  32007. if (data) {
  32008. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32009. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32010. }
  32011. if (this.subMeshes) {
  32012. for (var index = 0; index < this.subMeshes.length; index++) {
  32013. this.subMeshes[index].refreshBoundingInfo();
  32014. }
  32015. }
  32016. this._updateBoundingInfo();
  32017. return this;
  32018. };
  32019. Mesh.prototype._getPositionData = function (applySkeleton) {
  32020. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32021. if (data && applySkeleton && this.skeleton) {
  32022. data = BABYLON.Tools.Slice(data);
  32023. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32024. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32025. if (matricesWeightsData && matricesIndicesData) {
  32026. var needExtras = this.numBoneInfluencers > 4;
  32027. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32028. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32029. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32030. var tempVector = BABYLON.Tmp.Vector3[0];
  32031. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32032. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32033. var matWeightIdx = 0;
  32034. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32035. finalMatrix.reset();
  32036. var inf;
  32037. var weight;
  32038. for (inf = 0; inf < 4; inf++) {
  32039. weight = matricesWeightsData[matWeightIdx + inf];
  32040. if (weight <= 0)
  32041. break;
  32042. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32043. finalMatrix.addToSelf(tempMatrix);
  32044. }
  32045. if (needExtras) {
  32046. for (inf = 0; inf < 4; inf++) {
  32047. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32048. if (weight <= 0)
  32049. break;
  32050. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32051. finalMatrix.addToSelf(tempMatrix);
  32052. }
  32053. }
  32054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32055. tempVector.toArray(data, index);
  32056. }
  32057. }
  32058. }
  32059. return data;
  32060. };
  32061. Mesh.prototype._createGlobalSubMesh = function (force) {
  32062. var totalVertices = this.getTotalVertices();
  32063. if (!totalVertices || !this.getIndices()) {
  32064. return null;
  32065. }
  32066. // Check if we need to recreate the submeshes
  32067. if (this.subMeshes && this.subMeshes.length > 0) {
  32068. var ib = this.getIndices();
  32069. if (!ib) {
  32070. return null;
  32071. }
  32072. var totalIndices = ib.length;
  32073. var needToRecreate = false;
  32074. if (force) {
  32075. needToRecreate = true;
  32076. }
  32077. else {
  32078. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32079. var submesh = _a[_i];
  32080. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32081. needToRecreate = true;
  32082. break;
  32083. }
  32084. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32085. needToRecreate = true;
  32086. break;
  32087. }
  32088. }
  32089. }
  32090. if (!needToRecreate) {
  32091. return this.subMeshes[0];
  32092. }
  32093. }
  32094. this.releaseSubMeshes();
  32095. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32096. };
  32097. Mesh.prototype.subdivide = function (count) {
  32098. if (count < 1) {
  32099. return;
  32100. }
  32101. var totalIndices = this.getTotalIndices();
  32102. var subdivisionSize = (totalIndices / count) | 0;
  32103. var offset = 0;
  32104. // Ensure that subdivisionSize is a multiple of 3
  32105. while (subdivisionSize % 3 !== 0) {
  32106. subdivisionSize++;
  32107. }
  32108. this.releaseSubMeshes();
  32109. for (var index = 0; index < count; index++) {
  32110. if (offset >= totalIndices) {
  32111. break;
  32112. }
  32113. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32114. offset += subdivisionSize;
  32115. }
  32116. this.synchronizeInstances();
  32117. };
  32118. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32119. if (updatable === void 0) { updatable = false; }
  32120. if (!this._geometry) {
  32121. var vertexData = new BABYLON.VertexData();
  32122. vertexData.set(data, kind);
  32123. var scene = this.getScene();
  32124. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32125. }
  32126. else {
  32127. this._geometry.setVerticesData(kind, data, updatable, stride);
  32128. }
  32129. return this;
  32130. };
  32131. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32132. if (updatable === void 0) { updatable = true; }
  32133. var vb = this.getVertexBuffer(kind);
  32134. if (!vb || vb.isUpdatable() === updatable) {
  32135. return;
  32136. }
  32137. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32138. };
  32139. /**
  32140. * Sets the mesh VertexBuffer.
  32141. * Returns the Mesh.
  32142. */
  32143. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32144. if (!this._geometry) {
  32145. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32146. }
  32147. this._geometry.setVerticesBuffer(buffer);
  32148. return this;
  32149. };
  32150. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32151. if (!this._geometry) {
  32152. return this;
  32153. }
  32154. if (!makeItUnique) {
  32155. this._geometry.updateVerticesData(kind, data, updateExtends);
  32156. }
  32157. else {
  32158. this.makeGeometryUnique();
  32159. this.updateVerticesData(kind, data, updateExtends, false);
  32160. }
  32161. return this;
  32162. };
  32163. /**
  32164. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32165. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32166. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32167. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32168. * Returns the Mesh.
  32169. */
  32170. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32171. if (computeNormals === void 0) { computeNormals = true; }
  32172. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32173. if (!positions) {
  32174. return this;
  32175. }
  32176. positionFunction(positions);
  32177. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32178. if (computeNormals) {
  32179. var indices = this.getIndices();
  32180. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32181. if (!normals) {
  32182. return this;
  32183. }
  32184. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32185. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32186. }
  32187. return this;
  32188. };
  32189. /**
  32190. * Creates a un-shared specific occurence of the geometry for the mesh.
  32191. * Returns the Mesh.
  32192. */
  32193. Mesh.prototype.makeGeometryUnique = function () {
  32194. if (!this._geometry) {
  32195. return this;
  32196. }
  32197. var oldGeometry = this._geometry;
  32198. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32199. oldGeometry.releaseForMesh(this, true);
  32200. geometry.applyToMesh(this);
  32201. return this;
  32202. };
  32203. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32204. if (totalVertices === void 0) { totalVertices = null; }
  32205. if (updatable === void 0) { updatable = false; }
  32206. if (!this._geometry) {
  32207. var vertexData = new BABYLON.VertexData();
  32208. vertexData.indices = indices;
  32209. var scene = this.getScene();
  32210. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32211. }
  32212. else {
  32213. this._geometry.setIndices(indices, totalVertices, updatable);
  32214. }
  32215. return this;
  32216. };
  32217. /**
  32218. * Update the current index buffer
  32219. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32220. * Returns the Mesh.
  32221. */
  32222. Mesh.prototype.updateIndices = function (indices, offset) {
  32223. if (!this._geometry) {
  32224. return this;
  32225. }
  32226. this._geometry.updateIndices(indices, offset);
  32227. return this;
  32228. };
  32229. /**
  32230. * Invert the geometry to move from a right handed system to a left handed one.
  32231. * Returns the Mesh.
  32232. */
  32233. Mesh.prototype.toLeftHanded = function () {
  32234. if (!this._geometry) {
  32235. return this;
  32236. }
  32237. this._geometry.toLeftHanded();
  32238. return this;
  32239. };
  32240. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32241. if (!this._geometry) {
  32242. return this;
  32243. }
  32244. var engine = this.getScene().getEngine();
  32245. // Wireframe
  32246. var indexToBind;
  32247. if (this._unIndexed) {
  32248. indexToBind = null;
  32249. }
  32250. else {
  32251. switch (fillMode) {
  32252. case BABYLON.Material.PointFillMode:
  32253. indexToBind = null;
  32254. break;
  32255. case BABYLON.Material.WireFrameFillMode:
  32256. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32257. break;
  32258. default:
  32259. case BABYLON.Material.TriangleFillMode:
  32260. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32261. break;
  32262. }
  32263. }
  32264. // VBOs
  32265. this._geometry._bind(effect, indexToBind);
  32266. return this;
  32267. };
  32268. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32269. if (alternate === void 0) { alternate = false; }
  32270. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32271. return this;
  32272. }
  32273. this.onBeforeDrawObservable.notifyObservers(this);
  32274. var scene = this.getScene();
  32275. var engine = scene.getEngine();
  32276. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32277. // or triangles as points
  32278. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32279. }
  32280. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32281. // Triangles as wireframe
  32282. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32283. }
  32284. else {
  32285. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32286. }
  32287. if (scene._isAlternateRenderingEnabled && !alternate) {
  32288. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32289. if (!effect || !scene.activeCamera) {
  32290. return this;
  32291. }
  32292. scene._switchToAlternateCameraConfiguration(true);
  32293. this._effectiveMaterial.bindView(effect);
  32294. this._effectiveMaterial.bindViewProjection(effect);
  32295. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32296. this._draw(subMesh, fillMode, instancesCount, true);
  32297. engine.setViewport(scene.activeCamera.viewport);
  32298. scene._switchToAlternateCameraConfiguration(false);
  32299. this._effectiveMaterial.bindView(effect);
  32300. this._effectiveMaterial.bindViewProjection(effect);
  32301. }
  32302. return this;
  32303. };
  32304. /**
  32305. * Registers for this mesh a javascript function called just before the rendering process.
  32306. * This function is passed the current mesh.
  32307. * Return the Mesh.
  32308. */
  32309. Mesh.prototype.registerBeforeRender = function (func) {
  32310. this.onBeforeRenderObservable.add(func);
  32311. return this;
  32312. };
  32313. /**
  32314. * Disposes a previously registered javascript function called before the rendering.
  32315. * This function is passed the current mesh.
  32316. * Returns the Mesh.
  32317. */
  32318. Mesh.prototype.unregisterBeforeRender = function (func) {
  32319. this.onBeforeRenderObservable.removeCallback(func);
  32320. return this;
  32321. };
  32322. /**
  32323. * Registers for this mesh a javascript function called just after the rendering is complete.
  32324. * This function is passed the current mesh.
  32325. * Returns the Mesh.
  32326. */
  32327. Mesh.prototype.registerAfterRender = function (func) {
  32328. this.onAfterRenderObservable.add(func);
  32329. return this;
  32330. };
  32331. /**
  32332. * Disposes a previously registered javascript function called after the rendering.
  32333. * This function is passed the current mesh.
  32334. * Return the Mesh.
  32335. */
  32336. Mesh.prototype.unregisterAfterRender = function (func) {
  32337. this.onAfterRenderObservable.removeCallback(func);
  32338. return this;
  32339. };
  32340. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32341. var scene = this.getScene();
  32342. this._batchCache.mustReturn = false;
  32343. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32344. this._batchCache.visibleInstances[subMeshId] = null;
  32345. if (this._visibleInstances) {
  32346. var currentRenderId = scene.getRenderId();
  32347. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32348. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32349. var selfRenderId = this._renderId;
  32350. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32351. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32352. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32353. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32354. }
  32355. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32356. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32357. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32358. this._batchCache.mustReturn = true;
  32359. return this._batchCache;
  32360. }
  32361. if (currentRenderId !== selfRenderId) {
  32362. this._batchCache.renderSelf[subMeshId] = false;
  32363. }
  32364. }
  32365. this._renderIdForInstances[subMeshId] = currentRenderId;
  32366. }
  32367. return this._batchCache;
  32368. };
  32369. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32370. var visibleInstances = batch.visibleInstances[subMesh._id];
  32371. if (!visibleInstances) {
  32372. return this;
  32373. }
  32374. var matricesCount = visibleInstances.length + 1;
  32375. var bufferSize = matricesCount * 16 * 4;
  32376. var currentInstancesBufferSize = this._instancesBufferSize;
  32377. var instancesBuffer = this._instancesBuffer;
  32378. while (this._instancesBufferSize < bufferSize) {
  32379. this._instancesBufferSize *= 2;
  32380. }
  32381. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32382. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32383. }
  32384. var offset = 0;
  32385. var instancesCount = 0;
  32386. var world = this.getWorldMatrix();
  32387. if (batch.renderSelf[subMesh._id]) {
  32388. world.copyToArray(this._instancesData, offset);
  32389. offset += 16;
  32390. instancesCount++;
  32391. }
  32392. if (visibleInstances) {
  32393. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32394. var instance = visibleInstances[instanceIndex];
  32395. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32396. offset += 16;
  32397. instancesCount++;
  32398. }
  32399. }
  32400. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32401. if (instancesBuffer) {
  32402. instancesBuffer.dispose();
  32403. }
  32404. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32405. this._instancesBuffer = instancesBuffer;
  32406. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32407. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32408. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32409. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32410. }
  32411. else {
  32412. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32413. }
  32414. this._bind(subMesh, effect, fillMode);
  32415. this._draw(subMesh, fillMode, instancesCount);
  32416. engine.unbindInstanceAttributes();
  32417. return this;
  32418. };
  32419. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32420. var scene = this.getScene();
  32421. var engine = scene.getEngine();
  32422. if (hardwareInstancedRendering) {
  32423. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32424. }
  32425. else {
  32426. if (batch.renderSelf[subMesh._id]) {
  32427. // Draw
  32428. if (onBeforeDraw) {
  32429. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32430. }
  32431. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32432. }
  32433. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32434. if (visibleInstancesForSubMesh) {
  32435. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32436. var instance = visibleInstancesForSubMesh[instanceIndex];
  32437. // World
  32438. var world = instance.getWorldMatrix();
  32439. if (onBeforeDraw) {
  32440. onBeforeDraw(true, world, effectiveMaterial);
  32441. }
  32442. // Draw
  32443. this._draw(subMesh, fillMode);
  32444. }
  32445. }
  32446. }
  32447. return this;
  32448. };
  32449. /**
  32450. * Triggers the draw call for the mesh.
  32451. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32452. * Returns the Mesh.
  32453. */
  32454. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32455. this._checkOcclusionQuery();
  32456. if (this._isOccluded) {
  32457. return this;
  32458. }
  32459. var scene = this.getScene();
  32460. // Managing instances
  32461. var batch = this._getInstancesRenderList(subMesh._id);
  32462. if (batch.mustReturn) {
  32463. return this;
  32464. }
  32465. // Checking geometry state
  32466. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32467. return this;
  32468. }
  32469. this.onBeforeRenderObservable.notifyObservers(this);
  32470. var engine = scene.getEngine();
  32471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32472. // Material
  32473. var material = subMesh.getMaterial();
  32474. if (!material) {
  32475. return this;
  32476. }
  32477. this._effectiveMaterial = material;
  32478. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32479. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32480. return this;
  32481. }
  32482. }
  32483. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32484. return this;
  32485. }
  32486. // Alpha mode
  32487. if (enableAlphaMode) {
  32488. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32489. }
  32490. // Outline - step 1
  32491. var savedDepthWrite = engine.getDepthWrite();
  32492. if (this.renderOutline) {
  32493. engine.setDepthWrite(false);
  32494. scene.getOutlineRenderer().render(subMesh, batch);
  32495. engine.setDepthWrite(savedDepthWrite);
  32496. }
  32497. var effect;
  32498. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32499. effect = subMesh.effect;
  32500. }
  32501. else {
  32502. effect = this._effectiveMaterial.getEffect();
  32503. }
  32504. if (!effect) {
  32505. return this;
  32506. }
  32507. var sideOrientation = this.overrideMaterialSideOrientation;
  32508. if (sideOrientation == null) {
  32509. sideOrientation = this._effectiveMaterial.sideOrientation;
  32510. if (this._getWorldMatrixDeterminant() < 0) {
  32511. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32512. }
  32513. }
  32514. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32515. if (this._effectiveMaterial.forceDepthWrite) {
  32516. engine.setDepthWrite(true);
  32517. }
  32518. // Bind
  32519. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32520. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32521. this._bind(subMesh, effect, fillMode);
  32522. }
  32523. var world = this.getWorldMatrix();
  32524. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32525. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32526. }
  32527. else {
  32528. this._effectiveMaterial.bind(world, this);
  32529. }
  32530. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32531. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32532. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32533. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32534. }
  32535. // Draw
  32536. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32537. // Unbind
  32538. this._effectiveMaterial.unbind();
  32539. // Outline - step 2
  32540. if (this.renderOutline && savedDepthWrite) {
  32541. engine.setDepthWrite(true);
  32542. engine.setColorWrite(false);
  32543. scene.getOutlineRenderer().render(subMesh, batch);
  32544. engine.setColorWrite(true);
  32545. }
  32546. // Overlay
  32547. if (this.renderOverlay) {
  32548. var currentMode = engine.getAlphaMode();
  32549. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32550. scene.getOutlineRenderer().render(subMesh, batch, true);
  32551. engine.setAlphaMode(currentMode);
  32552. }
  32553. this.onAfterRenderObservable.notifyObservers(this);
  32554. return this;
  32555. };
  32556. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32557. if (isInstance && effectiveMaterial) {
  32558. effectiveMaterial.bindOnlyWorldMatrix(world);
  32559. }
  32560. };
  32561. /**
  32562. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32563. */
  32564. Mesh.prototype.getEmittedParticleSystems = function () {
  32565. var results = new Array();
  32566. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32567. var particleSystem = this.getScene().particleSystems[index];
  32568. if (particleSystem.emitter === this) {
  32569. results.push(particleSystem);
  32570. }
  32571. }
  32572. return results;
  32573. };
  32574. /**
  32575. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32576. */
  32577. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32578. var results = new Array();
  32579. var descendants = this.getDescendants();
  32580. descendants.push(this);
  32581. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32582. var particleSystem = this.getScene().particleSystems[index];
  32583. var emitter = particleSystem.emitter;
  32584. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32585. results.push(particleSystem);
  32586. }
  32587. }
  32588. return results;
  32589. };
  32590. /**
  32591. * Normalize matrix weights so that all vertices have a total weight set to 1
  32592. */
  32593. Mesh.prototype.cleanMatrixWeights = function () {
  32594. var epsilon = 1e-3;
  32595. var noInfluenceBoneIndex = 0.0;
  32596. if (this.skeleton) {
  32597. noInfluenceBoneIndex = this.skeleton.bones.length;
  32598. }
  32599. else {
  32600. return;
  32601. }
  32602. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32603. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32604. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32605. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32606. var influencers = this.numBoneInfluencers;
  32607. var size = matricesWeights.length;
  32608. for (var i = 0; i < size; i += 4) {
  32609. var weight = 0.0;
  32610. var firstZeroWeight = -1;
  32611. for (var j = 0; j < 4; j++) {
  32612. var w = matricesWeights[i + j];
  32613. weight += w;
  32614. if (w < epsilon && firstZeroWeight < 0) {
  32615. firstZeroWeight = j;
  32616. }
  32617. }
  32618. if (matricesWeightsExtra) {
  32619. for (var j = 0; j < 4; j++) {
  32620. var w = matricesWeightsExtra[i + j];
  32621. weight += w;
  32622. if (w < epsilon && firstZeroWeight < 0) {
  32623. firstZeroWeight = j + 4;
  32624. }
  32625. }
  32626. }
  32627. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32628. firstZeroWeight = influencers - 1;
  32629. }
  32630. if (weight > epsilon) {
  32631. var mweight = 1.0 / weight;
  32632. for (var j = 0; j < 4; j++) {
  32633. matricesWeights[i + j] *= mweight;
  32634. }
  32635. if (matricesWeightsExtra) {
  32636. for (var j = 0; j < 4; j++) {
  32637. matricesWeightsExtra[i + j] *= mweight;
  32638. }
  32639. }
  32640. }
  32641. else {
  32642. if (firstZeroWeight >= 4) {
  32643. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32644. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32645. }
  32646. else {
  32647. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32648. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32649. }
  32650. }
  32651. }
  32652. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32653. if (matricesIndicesExtra) {
  32654. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32655. }
  32656. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32657. if (matricesWeightsExtra) {
  32658. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32659. }
  32660. };
  32661. Mesh.prototype._checkDelayState = function () {
  32662. var scene = this.getScene();
  32663. if (this._geometry) {
  32664. this._geometry.load(scene);
  32665. }
  32666. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32668. this._queueLoad(scene);
  32669. }
  32670. return this;
  32671. };
  32672. Mesh.prototype._queueLoad = function (scene) {
  32673. var _this = this;
  32674. scene._addPendingData(this);
  32675. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32676. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32677. if (data instanceof ArrayBuffer) {
  32678. _this._delayLoadingFunction(data, _this);
  32679. }
  32680. else {
  32681. _this._delayLoadingFunction(JSON.parse(data), _this);
  32682. }
  32683. _this.instances.forEach(function (instance) {
  32684. instance._syncSubMeshes();
  32685. });
  32686. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32687. scene._removePendingData(_this);
  32688. }, function () { }, scene.database, getBinaryData);
  32689. return this;
  32690. };
  32691. /**
  32692. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32693. */
  32694. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32695. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32696. return false;
  32697. }
  32698. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32699. return false;
  32700. }
  32701. this._checkDelayState();
  32702. return true;
  32703. };
  32704. /**
  32705. * Sets the mesh material by the material or multiMaterial `id` property.
  32706. * The material `id` is a string identifying the material or the multiMaterial.
  32707. * This method returns the Mesh.
  32708. */
  32709. Mesh.prototype.setMaterialByID = function (id) {
  32710. var materials = this.getScene().materials;
  32711. var index;
  32712. for (index = materials.length - 1; index > -1; index--) {
  32713. if (materials[index].id === id) {
  32714. this.material = materials[index];
  32715. return this;
  32716. }
  32717. }
  32718. // Multi
  32719. var multiMaterials = this.getScene().multiMaterials;
  32720. for (index = multiMaterials.length - 1; index > -1; index--) {
  32721. if (multiMaterials[index].id === id) {
  32722. this.material = multiMaterials[index];
  32723. return this;
  32724. }
  32725. }
  32726. return this;
  32727. };
  32728. /**
  32729. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32730. */
  32731. Mesh.prototype.getAnimatables = function () {
  32732. var results = new Array();
  32733. if (this.material) {
  32734. results.push(this.material);
  32735. }
  32736. if (this.skeleton) {
  32737. results.push(this.skeleton);
  32738. }
  32739. return results;
  32740. };
  32741. /**
  32742. * Modifies the mesh geometry according to the passed transformation matrix.
  32743. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32744. * The mesh normals are modified accordingly the same transformation.
  32745. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32746. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32747. * Returns the Mesh.
  32748. */
  32749. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32750. // Position
  32751. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32752. return this;
  32753. }
  32754. var submeshes = this.subMeshes.splice(0);
  32755. this._resetPointsArrayCache();
  32756. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32757. var temp = new Array();
  32758. var index;
  32759. for (index = 0; index < data.length; index += 3) {
  32760. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32761. }
  32762. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32763. // Normals
  32764. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32765. return this;
  32766. }
  32767. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32768. temp = [];
  32769. for (index = 0; index < data.length; index += 3) {
  32770. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32771. }
  32772. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32773. // flip faces?
  32774. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32775. this.flipFaces();
  32776. }
  32777. // Restore submeshes
  32778. this.releaseSubMeshes();
  32779. this.subMeshes = submeshes;
  32780. return this;
  32781. };
  32782. /**
  32783. * Modifies the mesh geometry according to its own current World Matrix.
  32784. * The mesh World Matrix is then reset.
  32785. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32786. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32787. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32788. * Returns the Mesh.
  32789. */
  32790. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32791. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32792. this.scaling.copyFromFloats(1, 1, 1);
  32793. this.position.copyFromFloats(0, 0, 0);
  32794. this.rotation.copyFromFloats(0, 0, 0);
  32795. //only if quaternion is already set
  32796. if (this.rotationQuaternion) {
  32797. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32798. }
  32799. this._worldMatrix = BABYLON.Matrix.Identity();
  32800. return this;
  32801. };
  32802. Object.defineProperty(Mesh.prototype, "_positions", {
  32803. // Cache
  32804. get: function () {
  32805. if (this._geometry) {
  32806. return this._geometry._positions;
  32807. }
  32808. return null;
  32809. },
  32810. enumerable: true,
  32811. configurable: true
  32812. });
  32813. Mesh.prototype._resetPointsArrayCache = function () {
  32814. if (this._geometry) {
  32815. this._geometry._resetPointsArrayCache();
  32816. }
  32817. return this;
  32818. };
  32819. Mesh.prototype._generatePointsArray = function () {
  32820. if (this._geometry) {
  32821. return this._geometry._generatePointsArray();
  32822. }
  32823. return false;
  32824. };
  32825. /**
  32826. * Returns a new Mesh object generated from the current mesh properties.
  32827. * This method must not get confused with createInstance().
  32828. * The parameter `name` is a string, the name given to the new mesh.
  32829. * The optional parameter `newParent` can be any Node object (default `null`).
  32830. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32831. * 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.
  32832. */
  32833. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32835. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32836. };
  32837. /**
  32838. * Releases resources associated with this mesh.
  32839. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32840. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32841. */
  32842. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32843. var _this = this;
  32844. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32845. this.morphTargetManager = null;
  32846. if (this._geometry) {
  32847. this._geometry.releaseForMesh(this, true);
  32848. }
  32849. // Sources
  32850. var meshes = this.getScene().meshes;
  32851. meshes.forEach(function (abstractMesh) {
  32852. var mesh = abstractMesh;
  32853. if (mesh._source && mesh._source === _this) {
  32854. mesh._source = null;
  32855. }
  32856. });
  32857. this._source = null;
  32858. // Instances
  32859. if (this._instancesBuffer) {
  32860. this._instancesBuffer.dispose();
  32861. this._instancesBuffer = null;
  32862. }
  32863. while (this.instances.length) {
  32864. this.instances[0].dispose();
  32865. }
  32866. // Effect layers.
  32867. var effectLayers = this.getScene().effectLayers;
  32868. for (var i = 0; i < effectLayers.length; i++) {
  32869. var effectLayer = effectLayers[i];
  32870. if (effectLayer) {
  32871. effectLayer._disposeMesh(this);
  32872. }
  32873. }
  32874. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32875. };
  32876. /**
  32877. * Modifies the mesh geometry according to a displacement map.
  32878. * 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.
  32879. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32880. * This method returns nothing.
  32881. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32882. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32883. * 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.
  32884. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32885. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32886. *
  32887. * Returns the Mesh.
  32888. */
  32889. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32890. var _this = this;
  32891. var scene = this.getScene();
  32892. var onload = function (img) {
  32893. // Getting height map data
  32894. var canvas = document.createElement("canvas");
  32895. var context = canvas.getContext("2d");
  32896. var heightMapWidth = img.width;
  32897. var heightMapHeight = img.height;
  32898. canvas.width = heightMapWidth;
  32899. canvas.height = heightMapHeight;
  32900. context.drawImage(img, 0, 0);
  32901. // Create VertexData from map data
  32902. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32903. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32904. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32905. //execute success callback, if set
  32906. if (onSuccess) {
  32907. onSuccess(_this);
  32908. }
  32909. };
  32910. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32911. return this;
  32912. };
  32913. /**
  32914. * Modifies the mesh geometry according to a displacementMap buffer.
  32915. * 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.
  32916. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32917. * This method returns nothing.
  32918. * 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.
  32919. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32920. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32921. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32922. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32923. *
  32924. * Returns the Mesh.
  32925. */
  32926. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32927. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32928. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32929. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32930. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32931. return this;
  32932. }
  32933. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32934. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32935. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32936. var position = BABYLON.Vector3.Zero();
  32937. var normal = BABYLON.Vector3.Zero();
  32938. var uv = BABYLON.Vector2.Zero();
  32939. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32940. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32941. for (var index = 0; index < positions.length; index += 3) {
  32942. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32943. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32944. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32945. // Compute height
  32946. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32947. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32948. var pos = (u + v * heightMapWidth) * 4;
  32949. var r = buffer[pos] / 255.0;
  32950. var g = buffer[pos + 1] / 255.0;
  32951. var b = buffer[pos + 2] / 255.0;
  32952. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32953. normal.normalize();
  32954. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32955. position = position.add(normal);
  32956. position.toArray(positions, index);
  32957. }
  32958. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32959. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32960. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32961. return this;
  32962. };
  32963. /**
  32964. * Modify the mesh to get a flat shading rendering.
  32965. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32966. * This method returns the Mesh.
  32967. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32968. */
  32969. Mesh.prototype.convertToFlatShadedMesh = function () {
  32970. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32971. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32972. var kinds = this.getVerticesDataKinds();
  32973. var vbs = {};
  32974. var data = {};
  32975. var newdata = {};
  32976. var updatableNormals = false;
  32977. var kindIndex;
  32978. var kind;
  32979. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32980. kind = kinds[kindIndex];
  32981. var vertexBuffer = this.getVertexBuffer(kind);
  32982. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32983. updatableNormals = vertexBuffer.isUpdatable();
  32984. kinds.splice(kindIndex, 1);
  32985. kindIndex--;
  32986. continue;
  32987. }
  32988. vbs[kind] = vertexBuffer;
  32989. data[kind] = vbs[kind].getData();
  32990. newdata[kind] = [];
  32991. }
  32992. // Save previous submeshes
  32993. var previousSubmeshes = this.subMeshes.slice(0);
  32994. var indices = this.getIndices();
  32995. var totalIndices = this.getTotalIndices();
  32996. // Generating unique vertices per face
  32997. var index;
  32998. for (index = 0; index < totalIndices; index++) {
  32999. var vertexIndex = indices[index];
  33000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33001. kind = kinds[kindIndex];
  33002. var stride = vbs[kind].getStrideSize();
  33003. for (var offset = 0; offset < stride; offset++) {
  33004. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33005. }
  33006. }
  33007. }
  33008. // Updating faces & normal
  33009. var normals = [];
  33010. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33011. for (index = 0; index < totalIndices; index += 3) {
  33012. indices[index] = index;
  33013. indices[index + 1] = index + 1;
  33014. indices[index + 2] = index + 2;
  33015. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33016. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33017. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33018. var p1p2 = p1.subtract(p2);
  33019. var p3p2 = p3.subtract(p2);
  33020. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33021. // Store same normals for every vertex
  33022. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33023. normals.push(normal.x);
  33024. normals.push(normal.y);
  33025. normals.push(normal.z);
  33026. }
  33027. }
  33028. this.setIndices(indices);
  33029. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33030. // Updating vertex buffers
  33031. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33032. kind = kinds[kindIndex];
  33033. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33034. }
  33035. // Updating submeshes
  33036. this.releaseSubMeshes();
  33037. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33038. var previousOne = previousSubmeshes[submeshIndex];
  33039. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33040. }
  33041. this.synchronizeInstances();
  33042. return this;
  33043. };
  33044. /**
  33045. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33046. * In other words, more vertices, no more indices and a single bigger VBO.
  33047. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33048. * Returns the Mesh.
  33049. */
  33050. Mesh.prototype.convertToUnIndexedMesh = function () {
  33051. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33052. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33053. var kinds = this.getVerticesDataKinds();
  33054. var vbs = {};
  33055. var data = {};
  33056. var newdata = {};
  33057. var kindIndex;
  33058. var kind;
  33059. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33060. kind = kinds[kindIndex];
  33061. var vertexBuffer = this.getVertexBuffer(kind);
  33062. vbs[kind] = vertexBuffer;
  33063. data[kind] = vbs[kind].getData();
  33064. newdata[kind] = [];
  33065. }
  33066. // Save previous submeshes
  33067. var previousSubmeshes = this.subMeshes.slice(0);
  33068. var indices = this.getIndices();
  33069. var totalIndices = this.getTotalIndices();
  33070. // Generating unique vertices per face
  33071. var index;
  33072. for (index = 0; index < totalIndices; index++) {
  33073. var vertexIndex = indices[index];
  33074. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33075. kind = kinds[kindIndex];
  33076. var stride = vbs[kind].getStrideSize();
  33077. for (var offset = 0; offset < stride; offset++) {
  33078. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33079. }
  33080. }
  33081. }
  33082. // Updating indices
  33083. for (index = 0; index < totalIndices; index += 3) {
  33084. indices[index] = index;
  33085. indices[index + 1] = index + 1;
  33086. indices[index + 2] = index + 2;
  33087. }
  33088. this.setIndices(indices);
  33089. // Updating vertex buffers
  33090. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33091. kind = kinds[kindIndex];
  33092. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33093. }
  33094. // Updating submeshes
  33095. this.releaseSubMeshes();
  33096. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33097. var previousOne = previousSubmeshes[submeshIndex];
  33098. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33099. }
  33100. this._unIndexed = true;
  33101. this.synchronizeInstances();
  33102. return this;
  33103. };
  33104. /**
  33105. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33106. * This method returns the Mesh.
  33107. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33108. */
  33109. Mesh.prototype.flipFaces = function (flipNormals) {
  33110. if (flipNormals === void 0) { flipNormals = false; }
  33111. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33112. var i;
  33113. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33114. for (i = 0; i < vertex_data.normals.length; i++) {
  33115. vertex_data.normals[i] *= -1;
  33116. }
  33117. }
  33118. if (vertex_data.indices) {
  33119. var temp;
  33120. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33121. // reassign indices
  33122. temp = vertex_data.indices[i + 1];
  33123. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33124. vertex_data.indices[i + 2] = temp;
  33125. }
  33126. }
  33127. vertex_data.applyToMesh(this);
  33128. return this;
  33129. };
  33130. // Instances
  33131. /**
  33132. * Creates a new InstancedMesh object from the mesh model.
  33133. * An instance shares the same properties and the same material than its model.
  33134. * Only these properties of each instance can then be set individually :
  33135. * - position
  33136. * - rotation
  33137. * - rotationQuaternion
  33138. * - setPivotMatrix
  33139. * - scaling
  33140. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33141. * Warning : this method is not supported for Line mesh and LineSystem
  33142. */
  33143. Mesh.prototype.createInstance = function (name) {
  33144. return new BABYLON.InstancedMesh(name, this);
  33145. };
  33146. /**
  33147. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33148. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33149. * This method returns the Mesh.
  33150. */
  33151. Mesh.prototype.synchronizeInstances = function () {
  33152. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33153. var instance = this.instances[instanceIndex];
  33154. instance._syncSubMeshes();
  33155. }
  33156. return this;
  33157. };
  33158. /**
  33159. * Simplify the mesh according to the given array of settings.
  33160. * Function will return immediately and will simplify async. It returns the Mesh.
  33161. * @param settings a collection of simplification settings.
  33162. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33163. * @param type the type of simplification to run.
  33164. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33165. */
  33166. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33167. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33168. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33169. this.getScene().simplificationQueue.addTask({
  33170. settings: settings,
  33171. parallelProcessing: parallelProcessing,
  33172. mesh: this,
  33173. simplificationType: simplificationType,
  33174. successCallback: successCallback
  33175. });
  33176. return this;
  33177. };
  33178. /**
  33179. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33180. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33181. * This should be used together with the simplification to avoid disappearing triangles.
  33182. * Returns the Mesh.
  33183. * @param successCallback an optional success callback to be called after the optimization finished.
  33184. */
  33185. Mesh.prototype.optimizeIndices = function (successCallback) {
  33186. var _this = this;
  33187. var indices = this.getIndices();
  33188. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33189. if (!positions || !indices) {
  33190. return this;
  33191. }
  33192. var vectorPositions = new Array();
  33193. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33194. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33195. }
  33196. var dupes = new Array();
  33197. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33198. var realPos = vectorPositions.length - 1 - iteration;
  33199. var testedPosition = vectorPositions[realPos];
  33200. for (var j = 0; j < realPos; ++j) {
  33201. var againstPosition = vectorPositions[j];
  33202. if (testedPosition.equals(againstPosition)) {
  33203. dupes[realPos] = j;
  33204. break;
  33205. }
  33206. }
  33207. }, function () {
  33208. for (var i = 0; i < indices.length; ++i) {
  33209. indices[i] = dupes[indices[i]] || indices[i];
  33210. }
  33211. //indices are now reordered
  33212. var originalSubMeshes = _this.subMeshes.slice(0);
  33213. _this.setIndices(indices);
  33214. _this.subMeshes = originalSubMeshes;
  33215. if (successCallback) {
  33216. successCallback(_this);
  33217. }
  33218. });
  33219. return this;
  33220. };
  33221. Mesh.prototype.serialize = function (serializationObject) {
  33222. serializationObject.name = this.name;
  33223. serializationObject.id = this.id;
  33224. serializationObject.type = this.getClassName();
  33225. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33226. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33227. }
  33228. serializationObject.position = this.position.asArray();
  33229. if (this.rotationQuaternion) {
  33230. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33231. }
  33232. else if (this.rotation) {
  33233. serializationObject.rotation = this.rotation.asArray();
  33234. }
  33235. serializationObject.scaling = this.scaling.asArray();
  33236. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33237. serializationObject.isEnabled = this.isEnabled(false);
  33238. serializationObject.isVisible = this.isVisible;
  33239. serializationObject.infiniteDistance = this.infiniteDistance;
  33240. serializationObject.pickable = this.isPickable;
  33241. serializationObject.receiveShadows = this.receiveShadows;
  33242. serializationObject.billboardMode = this.billboardMode;
  33243. serializationObject.visibility = this.visibility;
  33244. serializationObject.checkCollisions = this.checkCollisions;
  33245. serializationObject.isBlocker = this.isBlocker;
  33246. // Parent
  33247. if (this.parent) {
  33248. serializationObject.parentId = this.parent.id;
  33249. }
  33250. // Geometry
  33251. serializationObject.isUnIndexed = this.isUnIndexed;
  33252. var geometry = this._geometry;
  33253. if (geometry) {
  33254. var geometryId = geometry.id;
  33255. serializationObject.geometryId = geometryId;
  33256. // SubMeshes
  33257. serializationObject.subMeshes = [];
  33258. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33259. var subMesh = this.subMeshes[subIndex];
  33260. serializationObject.subMeshes.push({
  33261. materialIndex: subMesh.materialIndex,
  33262. verticesStart: subMesh.verticesStart,
  33263. verticesCount: subMesh.verticesCount,
  33264. indexStart: subMesh.indexStart,
  33265. indexCount: subMesh.indexCount
  33266. });
  33267. }
  33268. }
  33269. // Material
  33270. if (this.material) {
  33271. serializationObject.materialId = this.material.id;
  33272. }
  33273. else {
  33274. this.material = null;
  33275. }
  33276. // Morph targets
  33277. if (this.morphTargetManager) {
  33278. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33279. }
  33280. // Skeleton
  33281. if (this.skeleton) {
  33282. serializationObject.skeletonId = this.skeleton.id;
  33283. }
  33284. // Physics
  33285. //TODO implement correct serialization for physics impostors.
  33286. var impostor = this.getPhysicsImpostor();
  33287. if (impostor) {
  33288. serializationObject.physicsMass = impostor.getParam("mass");
  33289. serializationObject.physicsFriction = impostor.getParam("friction");
  33290. serializationObject.physicsRestitution = impostor.getParam("mass");
  33291. serializationObject.physicsImpostor = impostor.type;
  33292. }
  33293. // Metadata
  33294. if (this.metadata) {
  33295. serializationObject.metadata = this.metadata;
  33296. }
  33297. // Instances
  33298. serializationObject.instances = [];
  33299. for (var index = 0; index < this.instances.length; index++) {
  33300. var instance = this.instances[index];
  33301. var serializationInstance = {
  33302. name: instance.name,
  33303. id: instance.id,
  33304. position: instance.position.asArray(),
  33305. scaling: instance.scaling.asArray()
  33306. };
  33307. if (instance.rotationQuaternion) {
  33308. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33309. }
  33310. else if (instance.rotation) {
  33311. serializationInstance.rotation = instance.rotation.asArray();
  33312. }
  33313. serializationObject.instances.push(serializationInstance);
  33314. // Animations
  33315. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33316. serializationInstance.ranges = instance.serializeAnimationRanges();
  33317. }
  33318. //
  33319. // Animations
  33320. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33321. serializationObject.ranges = this.serializeAnimationRanges();
  33322. // Layer mask
  33323. serializationObject.layerMask = this.layerMask;
  33324. // Alpha
  33325. serializationObject.alphaIndex = this.alphaIndex;
  33326. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33327. // Overlay
  33328. serializationObject.overlayAlpha = this.overlayAlpha;
  33329. serializationObject.overlayColor = this.overlayColor.asArray();
  33330. serializationObject.renderOverlay = this.renderOverlay;
  33331. // Fog
  33332. serializationObject.applyFog = this.applyFog;
  33333. // Action Manager
  33334. if (this.actionManager) {
  33335. serializationObject.actions = this.actionManager.serialize(this.name);
  33336. }
  33337. };
  33338. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33339. if (!this.geometry) {
  33340. return;
  33341. }
  33342. this._markSubMeshesAsAttributesDirty();
  33343. var morphTargetManager = this._morphTargetManager;
  33344. if (morphTargetManager && morphTargetManager.vertexCount) {
  33345. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33346. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33347. this.morphTargetManager = null;
  33348. return;
  33349. }
  33350. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33351. var morphTarget = morphTargetManager.getActiveTarget(index);
  33352. var positions = morphTarget.getPositions();
  33353. if (!positions) {
  33354. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33355. return;
  33356. }
  33357. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33358. var normals = morphTarget.getNormals();
  33359. if (normals) {
  33360. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33361. }
  33362. var tangents = morphTarget.getTangents();
  33363. if (tangents) {
  33364. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33365. }
  33366. }
  33367. }
  33368. else {
  33369. var index = 0;
  33370. // Positions
  33371. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33372. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33373. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33374. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33375. }
  33376. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33377. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33378. }
  33379. index++;
  33380. }
  33381. }
  33382. };
  33383. // Statics
  33384. /**
  33385. * Returns a new Mesh object parsed from the source provided.
  33386. * The parameter `parsedMesh` is the source.
  33387. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33388. */
  33389. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33390. var mesh;
  33391. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33392. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33393. }
  33394. else {
  33395. mesh = new Mesh(parsedMesh.name, scene);
  33396. }
  33397. mesh.id = parsedMesh.id;
  33398. if (BABYLON.Tags) {
  33399. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33400. }
  33401. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33402. if (parsedMesh.metadata !== undefined) {
  33403. mesh.metadata = parsedMesh.metadata;
  33404. }
  33405. if (parsedMesh.rotationQuaternion) {
  33406. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33407. }
  33408. else if (parsedMesh.rotation) {
  33409. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33410. }
  33411. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33412. if (parsedMesh.localMatrix) {
  33413. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33414. }
  33415. else if (parsedMesh.pivotMatrix) {
  33416. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33417. }
  33418. mesh.setEnabled(parsedMesh.isEnabled);
  33419. mesh.isVisible = parsedMesh.isVisible;
  33420. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33421. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33422. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33423. if (parsedMesh.applyFog !== undefined) {
  33424. mesh.applyFog = parsedMesh.applyFog;
  33425. }
  33426. if (parsedMesh.pickable !== undefined) {
  33427. mesh.isPickable = parsedMesh.pickable;
  33428. }
  33429. if (parsedMesh.alphaIndex !== undefined) {
  33430. mesh.alphaIndex = parsedMesh.alphaIndex;
  33431. }
  33432. mesh.receiveShadows = parsedMesh.receiveShadows;
  33433. mesh.billboardMode = parsedMesh.billboardMode;
  33434. if (parsedMesh.visibility !== undefined) {
  33435. mesh.visibility = parsedMesh.visibility;
  33436. }
  33437. mesh.checkCollisions = parsedMesh.checkCollisions;
  33438. if (parsedMesh.isBlocker !== undefined) {
  33439. mesh.isBlocker = parsedMesh.isBlocker;
  33440. }
  33441. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33442. // freezeWorldMatrix
  33443. if (parsedMesh.freezeWorldMatrix) {
  33444. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33445. }
  33446. // Parent
  33447. if (parsedMesh.parentId) {
  33448. mesh._waitingParentId = parsedMesh.parentId;
  33449. }
  33450. // Actions
  33451. if (parsedMesh.actions !== undefined) {
  33452. mesh._waitingActions = parsedMesh.actions;
  33453. }
  33454. // Overlay
  33455. if (parsedMesh.overlayAlpha !== undefined) {
  33456. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33457. }
  33458. if (parsedMesh.overlayColor !== undefined) {
  33459. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33460. }
  33461. if (parsedMesh.renderOverlay !== undefined) {
  33462. mesh.renderOverlay = parsedMesh.renderOverlay;
  33463. }
  33464. // Geometry
  33465. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33466. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33467. if (parsedMesh.delayLoadingFile) {
  33468. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33469. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33470. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33471. if (parsedMesh._binaryInfo) {
  33472. mesh._binaryInfo = parsedMesh._binaryInfo;
  33473. }
  33474. mesh._delayInfo = [];
  33475. if (parsedMesh.hasUVs) {
  33476. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33477. }
  33478. if (parsedMesh.hasUVs2) {
  33479. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33480. }
  33481. if (parsedMesh.hasUVs3) {
  33482. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33483. }
  33484. if (parsedMesh.hasUVs4) {
  33485. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33486. }
  33487. if (parsedMesh.hasUVs5) {
  33488. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33489. }
  33490. if (parsedMesh.hasUVs6) {
  33491. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33492. }
  33493. if (parsedMesh.hasColors) {
  33494. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33495. }
  33496. if (parsedMesh.hasMatricesIndices) {
  33497. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33498. }
  33499. if (parsedMesh.hasMatricesWeights) {
  33500. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33501. }
  33502. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33503. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33504. mesh._checkDelayState();
  33505. }
  33506. }
  33507. else {
  33508. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33509. }
  33510. // Material
  33511. if (parsedMesh.materialId) {
  33512. mesh.setMaterialByID(parsedMesh.materialId);
  33513. }
  33514. else {
  33515. mesh.material = null;
  33516. }
  33517. // Morph targets
  33518. if (parsedMesh.morphTargetManagerId > -1) {
  33519. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33520. }
  33521. // Skeleton
  33522. if (parsedMesh.skeletonId > -1) {
  33523. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33524. if (parsedMesh.numBoneInfluencers) {
  33525. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33526. }
  33527. }
  33528. // Animations
  33529. if (parsedMesh.animations) {
  33530. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33531. var parsedAnimation = parsedMesh.animations[animationIndex];
  33532. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33533. }
  33534. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33535. }
  33536. if (parsedMesh.autoAnimate) {
  33537. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33538. }
  33539. // Layer Mask
  33540. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33541. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33542. }
  33543. else {
  33544. mesh.layerMask = 0x0FFFFFFF;
  33545. }
  33546. // Physics
  33547. if (parsedMesh.physicsImpostor) {
  33548. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33549. mass: parsedMesh.physicsMass,
  33550. friction: parsedMesh.physicsFriction,
  33551. restitution: parsedMesh.physicsRestitution
  33552. }, scene);
  33553. }
  33554. // Instances
  33555. if (parsedMesh.instances) {
  33556. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33557. var parsedInstance = parsedMesh.instances[index];
  33558. var instance = mesh.createInstance(parsedInstance.name);
  33559. if (parsedInstance.id) {
  33560. instance.id = parsedInstance.id;
  33561. }
  33562. if (BABYLON.Tags) {
  33563. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33564. }
  33565. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33566. if (parsedInstance.parentId) {
  33567. instance._waitingParentId = parsedInstance.parentId;
  33568. }
  33569. if (parsedInstance.rotationQuaternion) {
  33570. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33571. }
  33572. else if (parsedInstance.rotation) {
  33573. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33574. }
  33575. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33576. instance.checkCollisions = mesh.checkCollisions;
  33577. if (parsedMesh.animations) {
  33578. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33579. parsedAnimation = parsedMesh.animations[animationIndex];
  33580. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33581. }
  33582. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33583. }
  33584. }
  33585. }
  33586. return mesh;
  33587. };
  33588. /**
  33589. * Creates a ribbon mesh.
  33590. * Please consider using the same method from the MeshBuilder class instead.
  33591. * 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.
  33592. *
  33593. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33594. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33595. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33596. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33597. * 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.
  33598. * 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.
  33599. * 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
  33600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33601. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33603. */
  33604. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33605. if (closeArray === void 0) { closeArray = false; }
  33606. if (updatable === void 0) { updatable = false; }
  33607. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33608. pathArray: pathArray,
  33609. closeArray: closeArray,
  33610. closePath: closePath,
  33611. offset: offset,
  33612. updatable: updatable,
  33613. sideOrientation: sideOrientation,
  33614. instance: instance
  33615. }, scene);
  33616. };
  33617. /**
  33618. * Creates a plane polygonal mesh. By default, this is a disc.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33621. * 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.
  33622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33623. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33625. */
  33626. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33627. if (scene === void 0) { scene = null; }
  33628. var options = {
  33629. radius: radius,
  33630. tessellation: tessellation,
  33631. sideOrientation: sideOrientation,
  33632. updatable: updatable
  33633. };
  33634. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33635. };
  33636. /**
  33637. * Creates a box mesh.
  33638. * Please consider using the same method from the MeshBuilder class instead.
  33639. * The parameter `size` sets the size (float) of each box side (default 1).
  33640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33641. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33643. */
  33644. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33645. if (scene === void 0) { scene = null; }
  33646. var options = {
  33647. size: size,
  33648. sideOrientation: sideOrientation,
  33649. updatable: updatable
  33650. };
  33651. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33652. };
  33653. /**
  33654. * Creates a sphere mesh.
  33655. * Please consider using the same method from the MeshBuilder class instead.
  33656. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33657. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33658. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33659. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33661. */
  33662. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33663. var options = {
  33664. segments: segments,
  33665. diameterX: diameter,
  33666. diameterY: diameter,
  33667. diameterZ: diameter,
  33668. sideOrientation: sideOrientation,
  33669. updatable: updatable
  33670. };
  33671. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33672. };
  33673. /**
  33674. * Creates a cylinder or a cone mesh.
  33675. * Please consider using the same method from the MeshBuilder class instead.
  33676. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33677. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33678. * 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.
  33679. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33680. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33682. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33684. */
  33685. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33686. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33687. if (scene !== undefined) {
  33688. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33689. updatable = scene;
  33690. }
  33691. scene = subdivisions;
  33692. subdivisions = 1;
  33693. }
  33694. var options = {
  33695. height: height,
  33696. diameterTop: diameterTop,
  33697. diameterBottom: diameterBottom,
  33698. tessellation: tessellation,
  33699. subdivisions: subdivisions,
  33700. sideOrientation: sideOrientation,
  33701. updatable: updatable
  33702. };
  33703. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33704. };
  33705. // Torus (Code from SharpDX.org)
  33706. /**
  33707. * Creates a torus mesh.
  33708. * Please consider using the same method from the MeshBuilder class instead.
  33709. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33710. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33711. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33713. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33715. */
  33716. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33717. var options = {
  33718. diameter: diameter,
  33719. thickness: thickness,
  33720. tessellation: tessellation,
  33721. sideOrientation: sideOrientation,
  33722. updatable: updatable
  33723. };
  33724. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates a torus knot mesh.
  33728. * Please consider using the same method from the MeshBuilder class instead.
  33729. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33730. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33731. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33732. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33733. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33734. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33736. */
  33737. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33738. var options = {
  33739. radius: radius,
  33740. tube: tube,
  33741. radialSegments: radialSegments,
  33742. tubularSegments: tubularSegments,
  33743. p: p,
  33744. q: q,
  33745. sideOrientation: sideOrientation,
  33746. updatable: updatable
  33747. };
  33748. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33749. };
  33750. /**
  33751. * Creates a line mesh.
  33752. * Please consider using the same method from the MeshBuilder class instead.
  33753. * 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.
  33754. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33755. * The parameter `points` is an array successive Vector3.
  33756. * 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
  33757. * When updating an instance, remember that only point positions can change, not the number of points.
  33758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33759. */
  33760. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33761. if (scene === void 0) { scene = null; }
  33762. if (updatable === void 0) { updatable = false; }
  33763. if (instance === void 0) { instance = null; }
  33764. var options = {
  33765. points: points,
  33766. updatable: updatable,
  33767. instance: instance
  33768. };
  33769. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33770. };
  33771. /**
  33772. * Creates a dashed line mesh.
  33773. * Please consider using the same method from the MeshBuilder class instead.
  33774. * 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.
  33775. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33776. * The parameter `points` is an array successive Vector3.
  33777. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33778. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33779. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33780. * 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
  33781. * When updating an instance, remember that only point positions can change, not the number of points.
  33782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33783. */
  33784. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33785. if (scene === void 0) { scene = null; }
  33786. var options = {
  33787. points: points,
  33788. dashSize: dashSize,
  33789. gapSize: gapSize,
  33790. dashNb: dashNb,
  33791. updatable: updatable,
  33792. instance: instance
  33793. };
  33794. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33795. };
  33796. /**
  33797. * Creates a polygon mesh.
  33798. * Please consider using the same method from the MeshBuilder class instead.
  33799. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33800. * 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.
  33801. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33803. * Remember you can only change the shape positions, not their number when updating a polygon.
  33804. */
  33805. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33806. var options = {
  33807. shape: shape,
  33808. holes: holes,
  33809. updatable: updatable,
  33810. sideOrientation: sideOrientation
  33811. };
  33812. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33813. };
  33814. /**
  33815. * Creates an extruded polygon mesh, with depth in the Y direction.
  33816. * Please consider using the same method from the MeshBuilder class instead.
  33817. */
  33818. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33819. var options = {
  33820. shape: shape,
  33821. holes: holes,
  33822. depth: depth,
  33823. updatable: updatable,
  33824. sideOrientation: sideOrientation
  33825. };
  33826. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33827. };
  33828. /**
  33829. * Creates an extruded shape mesh.
  33830. * 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.
  33831. * Please consider using the same method from the MeshBuilder class instead.
  33832. *
  33833. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33834. * 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
  33835. * extruded along the Z axis.
  33836. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33837. * 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.
  33838. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33839. * 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
  33840. * 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
  33841. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33842. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33843. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33845. */
  33846. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33847. if (scene === void 0) { scene = null; }
  33848. var options = {
  33849. shape: shape,
  33850. path: path,
  33851. scale: scale,
  33852. rotation: rotation,
  33853. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33854. sideOrientation: sideOrientation,
  33855. instance: instance,
  33856. updatable: updatable
  33857. };
  33858. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33859. };
  33860. /**
  33861. * Creates an custom extruded shape mesh.
  33862. * 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.
  33863. * Please consider using the same method from the MeshBuilder class instead.
  33864. *
  33865. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33866. * 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
  33867. * extruded along the Z axis.
  33868. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33869. * 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
  33870. * and the distance of this point from the begining of the path :
  33871. * ```javascript
  33872. * var rotationFunction = function(i, distance) {
  33873. * // do things
  33874. * return rotationValue; }
  33875. * ```
  33876. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33877. * 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
  33878. * and the distance of this point from the begining of the path :
  33879. * ```javascript
  33880. * var scaleFunction = function(i, distance) {
  33881. * // do things
  33882. * return scaleValue;}
  33883. * ```
  33884. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33885. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33886. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33887. * 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
  33888. * 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
  33889. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33890. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33891. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33893. */
  33894. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33895. var options = {
  33896. shape: shape,
  33897. path: path,
  33898. scaleFunction: scaleFunction,
  33899. rotationFunction: rotationFunction,
  33900. ribbonCloseArray: ribbonCloseArray,
  33901. ribbonClosePath: ribbonClosePath,
  33902. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33903. sideOrientation: sideOrientation,
  33904. instance: instance,
  33905. updatable: updatable
  33906. };
  33907. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33908. };
  33909. /**
  33910. * Creates lathe mesh.
  33911. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33912. * Please consider using the same method from the MeshBuilder class instead.
  33913. * 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
  33914. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33915. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33916. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33918. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33920. */
  33921. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33922. var options = {
  33923. shape: shape,
  33924. radius: radius,
  33925. tessellation: tessellation,
  33926. sideOrientation: sideOrientation,
  33927. updatable: updatable
  33928. };
  33929. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33930. };
  33931. /**
  33932. * Creates a plane mesh.
  33933. * Please consider using the same method from the MeshBuilder class instead.
  33934. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33936. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33938. */
  33939. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33940. var options = {
  33941. size: size,
  33942. width: size,
  33943. height: size,
  33944. sideOrientation: sideOrientation,
  33945. updatable: updatable
  33946. };
  33947. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33948. };
  33949. /**
  33950. * Creates a ground mesh.
  33951. * Please consider using the same method from the MeshBuilder class instead.
  33952. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33953. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33955. */
  33956. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33957. var options = {
  33958. width: width,
  33959. height: height,
  33960. subdivisions: subdivisions,
  33961. updatable: updatable
  33962. };
  33963. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33964. };
  33965. /**
  33966. * Creates a tiled ground mesh.
  33967. * Please consider using the same method from the MeshBuilder class instead.
  33968. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33969. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33970. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33971. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33972. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33973. * numbers of subdivisions on the ground width and height of each tile.
  33974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33975. */
  33976. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33977. var options = {
  33978. xmin: xmin,
  33979. zmin: zmin,
  33980. xmax: xmax,
  33981. zmax: zmax,
  33982. subdivisions: subdivisions,
  33983. precision: precision,
  33984. updatable: updatable
  33985. };
  33986. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33987. };
  33988. /**
  33989. * Creates a ground mesh from a height map.
  33990. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33991. * Please consider using the same method from the MeshBuilder class instead.
  33992. * The parameter `url` sets the URL of the height map image resource.
  33993. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33994. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33995. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33996. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33997. * 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).
  33998. * This function is passed the newly built mesh :
  33999. * ```javascript
  34000. * function(mesh) { // do things
  34001. * return; }
  34002. * ```
  34003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34004. */
  34005. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34006. var options = {
  34007. width: width,
  34008. height: height,
  34009. subdivisions: subdivisions,
  34010. minHeight: minHeight,
  34011. maxHeight: maxHeight,
  34012. updatable: updatable,
  34013. onReady: onReady
  34014. };
  34015. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34016. };
  34017. /**
  34018. * Creates a tube mesh.
  34019. * 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.
  34020. * Please consider using the same method from the MeshBuilder class instead.
  34021. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34022. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34023. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34024. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34025. * 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.
  34026. * It must return a radius value (positive float) :
  34027. * ```javascript
  34028. * var radiusFunction = function(i, distance) {
  34029. * // do things
  34030. * return radius; }
  34031. * ```
  34032. * 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
  34033. * 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
  34034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34035. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34037. */
  34038. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34039. var options = {
  34040. path: path,
  34041. radius: radius,
  34042. tessellation: tessellation,
  34043. radiusFunction: radiusFunction,
  34044. arc: 1,
  34045. cap: cap,
  34046. updatable: updatable,
  34047. sideOrientation: sideOrientation,
  34048. instance: instance
  34049. };
  34050. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34051. };
  34052. /**
  34053. * Creates a polyhedron mesh.
  34054. * Please consider using the same method from the MeshBuilder class instead.
  34055. * 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
  34056. * to choose the wanted type.
  34057. * The parameter `size` (positive float, default 1) sets the polygon size.
  34058. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34059. * 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`.
  34060. * 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
  34061. * 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)`).
  34062. * 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
  34063. * 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.
  34064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34065. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34067. */
  34068. Mesh.CreatePolyhedron = function (name, options, scene) {
  34069. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34070. };
  34071. /**
  34072. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34073. * Please consider using the same method from the MeshBuilder class instead.
  34074. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34075. * 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`).
  34076. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34077. * 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.
  34078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34079. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34081. */
  34082. Mesh.CreateIcoSphere = function (name, options, scene) {
  34083. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34084. };
  34085. /**
  34086. * Creates a decal mesh.
  34087. * Please consider using the same method from the MeshBuilder class instead.
  34088. * 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.
  34089. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34090. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34091. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34092. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34093. */
  34094. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34095. var options = {
  34096. position: position,
  34097. normal: normal,
  34098. size: size,
  34099. angle: angle
  34100. };
  34101. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34102. };
  34103. // Skeletons
  34104. /**
  34105. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34106. */
  34107. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34108. if (!this._sourcePositions) {
  34109. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34110. if (!source) {
  34111. return this._sourcePositions;
  34112. }
  34113. this._sourcePositions = new Float32Array(source);
  34114. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34115. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34116. }
  34117. }
  34118. return this._sourcePositions;
  34119. };
  34120. /**
  34121. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34122. */
  34123. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34124. if (!this._sourceNormals) {
  34125. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34126. if (!source) {
  34127. return this._sourceNormals;
  34128. }
  34129. this._sourceNormals = new Float32Array(source);
  34130. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34131. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34132. }
  34133. }
  34134. return this._sourceNormals;
  34135. };
  34136. /**
  34137. * Updates the vertex buffer by applying transformation from the bones.
  34138. * Returns the Mesh.
  34139. *
  34140. * @param {skeleton} skeleton to apply
  34141. */
  34142. Mesh.prototype.applySkeleton = function (skeleton) {
  34143. if (!this.geometry) {
  34144. return this;
  34145. }
  34146. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34147. return this;
  34148. }
  34149. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34150. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34151. return this;
  34152. }
  34153. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34154. return this;
  34155. }
  34156. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34157. return this;
  34158. }
  34159. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34160. return this;
  34161. }
  34162. if (!this._sourcePositions) {
  34163. var submeshes = this.subMeshes.slice();
  34164. this.setPositionsForCPUSkinning();
  34165. this.subMeshes = submeshes;
  34166. }
  34167. if (!this._sourceNormals) {
  34168. this.setNormalsForCPUSkinning();
  34169. }
  34170. // positionsData checks for not being Float32Array will only pass at most once
  34171. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34172. if (!positionsData) {
  34173. return this;
  34174. }
  34175. if (!(positionsData instanceof Float32Array)) {
  34176. positionsData = new Float32Array(positionsData);
  34177. }
  34178. // normalsData checks for not being Float32Array will only pass at most once
  34179. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34180. if (!normalsData) {
  34181. return this;
  34182. }
  34183. if (!(normalsData instanceof Float32Array)) {
  34184. normalsData = new Float32Array(normalsData);
  34185. }
  34186. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34187. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34188. if (!matricesWeightsData || !matricesIndicesData) {
  34189. return this;
  34190. }
  34191. var needExtras = this.numBoneInfluencers > 4;
  34192. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34193. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34194. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34195. var tempVector3 = BABYLON.Vector3.Zero();
  34196. var finalMatrix = new BABYLON.Matrix();
  34197. var tempMatrix = new BABYLON.Matrix();
  34198. var matWeightIdx = 0;
  34199. var inf;
  34200. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34201. var weight;
  34202. for (inf = 0; inf < 4; inf++) {
  34203. weight = matricesWeightsData[matWeightIdx + inf];
  34204. if (weight > 0) {
  34205. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34206. finalMatrix.addToSelf(tempMatrix);
  34207. }
  34208. else
  34209. break;
  34210. }
  34211. if (needExtras) {
  34212. for (inf = 0; inf < 4; inf++) {
  34213. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34214. if (weight > 0) {
  34215. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34216. finalMatrix.addToSelf(tempMatrix);
  34217. }
  34218. else
  34219. break;
  34220. }
  34221. }
  34222. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34223. tempVector3.toArray(positionsData, index);
  34224. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34225. tempVector3.toArray(normalsData, index);
  34226. finalMatrix.reset();
  34227. }
  34228. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34229. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34230. return this;
  34231. };
  34232. // Tools
  34233. /**
  34234. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34235. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34236. */
  34237. Mesh.MinMax = function (meshes) {
  34238. var minVector = null;
  34239. var maxVector = null;
  34240. meshes.forEach(function (mesh, index, array) {
  34241. var boundingInfo = mesh.getBoundingInfo();
  34242. var boundingBox = boundingInfo.boundingBox;
  34243. if (!minVector || !maxVector) {
  34244. minVector = boundingBox.minimumWorld;
  34245. maxVector = boundingBox.maximumWorld;
  34246. }
  34247. else {
  34248. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34249. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34250. }
  34251. });
  34252. if (!minVector || !maxVector) {
  34253. return {
  34254. min: BABYLON.Vector3.Zero(),
  34255. max: BABYLON.Vector3.Zero()
  34256. };
  34257. }
  34258. return {
  34259. min: minVector,
  34260. max: maxVector
  34261. };
  34262. };
  34263. /**
  34264. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34265. */
  34266. Mesh.Center = function (meshesOrMinMaxVector) {
  34267. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34268. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34269. };
  34270. /**
  34271. * Merge the array of meshes into a single mesh for performance reasons.
  34272. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34273. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34274. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34275. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34276. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34277. */
  34278. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34279. if (disposeSource === void 0) { disposeSource = true; }
  34280. var index;
  34281. if (!allow32BitsIndices) {
  34282. var totalVertices = 0;
  34283. // Counting vertices
  34284. for (index = 0; index < meshes.length; index++) {
  34285. if (meshes[index]) {
  34286. totalVertices += meshes[index].getTotalVertices();
  34287. if (totalVertices > 65536) {
  34288. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34289. return null;
  34290. }
  34291. }
  34292. }
  34293. }
  34294. // Merge
  34295. var vertexData = null;
  34296. var otherVertexData;
  34297. var indiceArray = new Array();
  34298. var source = null;
  34299. for (index = 0; index < meshes.length; index++) {
  34300. if (meshes[index]) {
  34301. meshes[index].computeWorldMatrix(true);
  34302. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34303. otherVertexData.transform(meshes[index].getWorldMatrix());
  34304. if (vertexData) {
  34305. vertexData.merge(otherVertexData);
  34306. }
  34307. else {
  34308. vertexData = otherVertexData;
  34309. source = meshes[index];
  34310. }
  34311. if (subdivideWithSubMeshes) {
  34312. indiceArray.push(meshes[index].getTotalIndices());
  34313. }
  34314. }
  34315. }
  34316. source = source;
  34317. if (!meshSubclass) {
  34318. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34319. }
  34320. vertexData.applyToMesh(meshSubclass);
  34321. // Setting properties
  34322. meshSubclass.material = source.material;
  34323. meshSubclass.checkCollisions = source.checkCollisions;
  34324. // Cleaning
  34325. if (disposeSource) {
  34326. for (index = 0; index < meshes.length; index++) {
  34327. if (meshes[index]) {
  34328. meshes[index].dispose();
  34329. }
  34330. }
  34331. }
  34332. // Subdivide
  34333. if (subdivideWithSubMeshes) {
  34334. //-- removal of global submesh
  34335. meshSubclass.releaseSubMeshes();
  34336. index = 0;
  34337. var offset = 0;
  34338. //-- apply subdivision according to index table
  34339. while (index < indiceArray.length) {
  34340. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34341. offset += indiceArray[index];
  34342. index++;
  34343. }
  34344. }
  34345. return meshSubclass;
  34346. };
  34347. // Consts
  34348. Mesh._FRONTSIDE = 0;
  34349. Mesh._BACKSIDE = 1;
  34350. Mesh._DOUBLESIDE = 2;
  34351. Mesh._DEFAULTSIDE = 0;
  34352. Mesh._NO_CAP = 0;
  34353. Mesh._CAP_START = 1;
  34354. Mesh._CAP_END = 2;
  34355. Mesh._CAP_ALL = 3;
  34356. return Mesh;
  34357. }(BABYLON.AbstractMesh));
  34358. BABYLON.Mesh = Mesh;
  34359. })(BABYLON || (BABYLON = {}));
  34360. //# sourceMappingURL=babylon.mesh.js.map
  34361. var BABYLON;
  34362. (function (BABYLON) {
  34363. var BaseSubMesh = /** @class */ (function () {
  34364. function BaseSubMesh() {
  34365. }
  34366. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34367. get: function () {
  34368. return this._materialEffect;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34374. if (defines === void 0) { defines = null; }
  34375. if (this._materialEffect === effect) {
  34376. if (!effect) {
  34377. this._materialDefines = null;
  34378. }
  34379. return;
  34380. }
  34381. this._materialDefines = defines;
  34382. this._materialEffect = effect;
  34383. };
  34384. return BaseSubMesh;
  34385. }());
  34386. BABYLON.BaseSubMesh = BaseSubMesh;
  34387. var SubMesh = /** @class */ (function (_super) {
  34388. __extends(SubMesh, _super);
  34389. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34390. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34391. var _this = _super.call(this) || this;
  34392. _this.materialIndex = materialIndex;
  34393. _this.verticesStart = verticesStart;
  34394. _this.verticesCount = verticesCount;
  34395. _this.indexStart = indexStart;
  34396. _this.indexCount = indexCount;
  34397. _this._renderId = 0;
  34398. _this._mesh = mesh;
  34399. _this._renderingMesh = renderingMesh || mesh;
  34400. mesh.subMeshes.push(_this);
  34401. _this._trianglePlanes = [];
  34402. _this._id = mesh.subMeshes.length - 1;
  34403. if (createBoundingBox) {
  34404. _this.refreshBoundingInfo();
  34405. mesh.computeWorldMatrix(true);
  34406. }
  34407. return _this;
  34408. }
  34409. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34410. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34411. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34412. };
  34413. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34414. get: function () {
  34415. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34416. },
  34417. enumerable: true,
  34418. configurable: true
  34419. });
  34420. /**
  34421. * Returns the submesh BoudingInfo object.
  34422. */
  34423. SubMesh.prototype.getBoundingInfo = function () {
  34424. if (this.IsGlobal) {
  34425. return this._mesh.getBoundingInfo();
  34426. }
  34427. return this._boundingInfo;
  34428. };
  34429. /**
  34430. * Sets the submesh BoundingInfo.
  34431. * Return the SubMesh.
  34432. */
  34433. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34434. this._boundingInfo = boundingInfo;
  34435. return this;
  34436. };
  34437. /**
  34438. * Returns the mesh of the current submesh.
  34439. */
  34440. SubMesh.prototype.getMesh = function () {
  34441. return this._mesh;
  34442. };
  34443. /**
  34444. * Returns the rendering mesh of the submesh.
  34445. */
  34446. SubMesh.prototype.getRenderingMesh = function () {
  34447. return this._renderingMesh;
  34448. };
  34449. /**
  34450. * Returns the submesh material.
  34451. */
  34452. SubMesh.prototype.getMaterial = function () {
  34453. var rootMaterial = this._renderingMesh.material;
  34454. if (rootMaterial === null || rootMaterial === undefined) {
  34455. return this._mesh.getScene().defaultMaterial;
  34456. }
  34457. else if (rootMaterial.getSubMaterial) {
  34458. var multiMaterial = rootMaterial;
  34459. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34460. if (this._currentMaterial !== effectiveMaterial) {
  34461. this._currentMaterial = effectiveMaterial;
  34462. this._materialDefines = null;
  34463. }
  34464. return effectiveMaterial;
  34465. }
  34466. return rootMaterial;
  34467. };
  34468. // Methods
  34469. /**
  34470. * Sets a new updated BoundingInfo object to the submesh.
  34471. * Returns the SubMesh.
  34472. */
  34473. SubMesh.prototype.refreshBoundingInfo = function () {
  34474. this._lastColliderWorldVertices = null;
  34475. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34476. return this;
  34477. }
  34478. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34479. if (!data) {
  34480. this._boundingInfo = this._mesh.getBoundingInfo();
  34481. return this;
  34482. }
  34483. var indices = this._renderingMesh.getIndices();
  34484. var extend;
  34485. //is this the only submesh?
  34486. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34487. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34488. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34489. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34490. }
  34491. else {
  34492. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34493. }
  34494. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34495. return this;
  34496. };
  34497. SubMesh.prototype._checkCollision = function (collider) {
  34498. var boundingInfo = this.getBoundingInfo();
  34499. return boundingInfo._checkCollision(collider);
  34500. };
  34501. /**
  34502. * Updates the submesh BoundingInfo.
  34503. * Returns the Submesh.
  34504. */
  34505. SubMesh.prototype.updateBoundingInfo = function (world) {
  34506. var boundingInfo = this.getBoundingInfo();
  34507. if (!boundingInfo) {
  34508. this.refreshBoundingInfo();
  34509. boundingInfo = this.getBoundingInfo();
  34510. }
  34511. boundingInfo.update(world);
  34512. return this;
  34513. };
  34514. /**
  34515. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34516. * Boolean returned.
  34517. */
  34518. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34519. var boundingInfo = this.getBoundingInfo();
  34520. if (!boundingInfo) {
  34521. return false;
  34522. }
  34523. return boundingInfo.isInFrustum(frustumPlanes);
  34524. };
  34525. /**
  34526. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34527. * Boolean returned.
  34528. */
  34529. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34530. var boundingInfo = this.getBoundingInfo();
  34531. if (!boundingInfo) {
  34532. return false;
  34533. }
  34534. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34535. };
  34536. /**
  34537. * Renders the submesh.
  34538. * Returns it.
  34539. */
  34540. SubMesh.prototype.render = function (enableAlphaMode) {
  34541. this._renderingMesh.render(this, enableAlphaMode);
  34542. return this;
  34543. };
  34544. /**
  34545. * Returns a new Index Buffer.
  34546. * Type returned : WebGLBuffer.
  34547. */
  34548. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34549. if (!this._linesIndexBuffer) {
  34550. var linesIndices = [];
  34551. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34552. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34553. }
  34554. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34555. this.linesIndexCount = linesIndices.length;
  34556. }
  34557. return this._linesIndexBuffer;
  34558. };
  34559. /**
  34560. * True is the passed Ray intersects the submesh bounding box.
  34561. * Boolean returned.
  34562. */
  34563. SubMesh.prototype.canIntersects = function (ray) {
  34564. var boundingInfo = this.getBoundingInfo();
  34565. if (!boundingInfo) {
  34566. return false;
  34567. }
  34568. return ray.intersectsBox(boundingInfo.boundingBox);
  34569. };
  34570. /**
  34571. * Returns an object IntersectionInfo.
  34572. */
  34573. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34574. var intersectInfo = null;
  34575. var material = this.getMaterial();
  34576. if (!material) {
  34577. return null;
  34578. }
  34579. switch (material.fillMode) {
  34580. case BABYLON.Material.PointListDrawMode:
  34581. case BABYLON.Material.LineListDrawMode:
  34582. case BABYLON.Material.LineLoopDrawMode:
  34583. case BABYLON.Material.LineStripDrawMode:
  34584. case BABYLON.Material.TriangleFanDrawMode:
  34585. case BABYLON.Material.TriangleStripDrawMode:
  34586. return null;
  34587. }
  34588. // LineMesh first as it's also a Mesh...
  34589. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34590. var lineMesh = this._mesh;
  34591. // Line test
  34592. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34593. var p0 = positions[indices[index]];
  34594. var p1 = positions[indices[index + 1]];
  34595. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34596. if (length < 0) {
  34597. continue;
  34598. }
  34599. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34600. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34601. if (fastCheck) {
  34602. break;
  34603. }
  34604. }
  34605. }
  34606. }
  34607. else {
  34608. // Triangles test
  34609. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34610. var p0 = positions[indices[index]];
  34611. var p1 = positions[indices[index + 1]];
  34612. var p2 = positions[indices[index + 2]];
  34613. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34614. if (currentIntersectInfo) {
  34615. if (currentIntersectInfo.distance < 0) {
  34616. continue;
  34617. }
  34618. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34619. intersectInfo = currentIntersectInfo;
  34620. intersectInfo.faceId = index / 3;
  34621. if (fastCheck) {
  34622. break;
  34623. }
  34624. }
  34625. }
  34626. }
  34627. }
  34628. return intersectInfo;
  34629. };
  34630. SubMesh.prototype._rebuild = function () {
  34631. if (this._linesIndexBuffer) {
  34632. this._linesIndexBuffer = null;
  34633. }
  34634. };
  34635. // Clone
  34636. /**
  34637. * Creates a new Submesh from the passed Mesh.
  34638. */
  34639. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34640. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34641. if (!this.IsGlobal) {
  34642. var boundingInfo = this.getBoundingInfo();
  34643. if (!boundingInfo) {
  34644. return result;
  34645. }
  34646. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34647. }
  34648. return result;
  34649. };
  34650. // Dispose
  34651. /**
  34652. * Disposes the Submesh.
  34653. * Returns nothing.
  34654. */
  34655. SubMesh.prototype.dispose = function () {
  34656. if (this._linesIndexBuffer) {
  34657. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34658. this._linesIndexBuffer = null;
  34659. }
  34660. // Remove from mesh
  34661. var index = this._mesh.subMeshes.indexOf(this);
  34662. this._mesh.subMeshes.splice(index, 1);
  34663. };
  34664. // Statics
  34665. /**
  34666. * Creates a new Submesh from the passed parameters :
  34667. * - materialIndex (integer) : the index of the main mesh material.
  34668. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34669. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34670. * - mesh (Mesh) : the main mesh to create the submesh from.
  34671. * - renderingMesh (optional Mesh) : rendering mesh.
  34672. */
  34673. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34674. var minVertexIndex = Number.MAX_VALUE;
  34675. var maxVertexIndex = -Number.MAX_VALUE;
  34676. renderingMesh = (renderingMesh || mesh);
  34677. var indices = renderingMesh.getIndices();
  34678. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34679. var vertexIndex = indices[index];
  34680. if (vertexIndex < minVertexIndex)
  34681. minVertexIndex = vertexIndex;
  34682. if (vertexIndex > maxVertexIndex)
  34683. maxVertexIndex = vertexIndex;
  34684. }
  34685. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34686. };
  34687. return SubMesh;
  34688. }(BaseSubMesh));
  34689. BABYLON.SubMesh = SubMesh;
  34690. })(BABYLON || (BABYLON = {}));
  34691. //# sourceMappingURL=babylon.subMesh.js.map
  34692. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34693. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34694. s = arguments[i];
  34695. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34696. t[p] = s[p];
  34697. }
  34698. return t;
  34699. };
  34700. var BABYLON;
  34701. (function (BABYLON) {
  34702. /**
  34703. * Manages the defines for the Material
  34704. */
  34705. var MaterialDefines = /** @class */ (function () {
  34706. function MaterialDefines() {
  34707. this._isDirty = true;
  34708. /** @hidden */
  34709. this._areLightsDirty = true;
  34710. /** @hidden */
  34711. this._areAttributesDirty = true;
  34712. /** @hidden */
  34713. this._areTexturesDirty = true;
  34714. /** @hidden */
  34715. this._areFresnelDirty = true;
  34716. /** @hidden */
  34717. this._areMiscDirty = true;
  34718. /** @hidden */
  34719. this._areImageProcessingDirty = true;
  34720. /** @hidden */
  34721. this._normals = false;
  34722. /** @hidden */
  34723. this._uvs = false;
  34724. /** @hidden */
  34725. this._needNormals = false;
  34726. /** @hidden */
  34727. this._needUVs = false;
  34728. }
  34729. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34730. /**
  34731. * Specifies if the material needs to be re-calculated
  34732. */
  34733. get: function () {
  34734. return this._isDirty;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. /**
  34740. * Marks the material to indicate that it has been re-calculated
  34741. */
  34742. MaterialDefines.prototype.markAsProcessed = function () {
  34743. this._isDirty = false;
  34744. this._areAttributesDirty = false;
  34745. this._areTexturesDirty = false;
  34746. this._areFresnelDirty = false;
  34747. this._areLightsDirty = false;
  34748. this._areMiscDirty = false;
  34749. this._areImageProcessingDirty = false;
  34750. };
  34751. /**
  34752. * Marks the material to indicate that it needs to be re-calculated
  34753. */
  34754. MaterialDefines.prototype.markAsUnprocessed = function () {
  34755. this._isDirty = true;
  34756. };
  34757. /**
  34758. * Marks the material to indicate all of its defines need to be re-calculated
  34759. */
  34760. MaterialDefines.prototype.markAllAsDirty = function () {
  34761. this._areTexturesDirty = true;
  34762. this._areAttributesDirty = true;
  34763. this._areLightsDirty = true;
  34764. this._areFresnelDirty = true;
  34765. this._areMiscDirty = true;
  34766. this._areImageProcessingDirty = true;
  34767. this._isDirty = true;
  34768. };
  34769. /**
  34770. * Marks the material to indicate that image processing needs to be re-calculated
  34771. */
  34772. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34773. this._areImageProcessingDirty = true;
  34774. this._isDirty = true;
  34775. };
  34776. /**
  34777. * Marks the material to indicate the lights need to be re-calculated
  34778. */
  34779. MaterialDefines.prototype.markAsLightDirty = function () {
  34780. this._areLightsDirty = true;
  34781. this._isDirty = true;
  34782. };
  34783. /**
  34784. * Marks the attribute state as changed
  34785. */
  34786. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34787. this._areAttributesDirty = true;
  34788. this._isDirty = true;
  34789. };
  34790. /**
  34791. * Marks the texture state as changed
  34792. */
  34793. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34794. this._areTexturesDirty = true;
  34795. this._isDirty = true;
  34796. };
  34797. /**
  34798. * Marks the fresnel state as changed
  34799. */
  34800. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34801. this._areFresnelDirty = true;
  34802. this._isDirty = true;
  34803. };
  34804. /**
  34805. * Marks the misc state as changed
  34806. */
  34807. MaterialDefines.prototype.markAsMiscDirty = function () {
  34808. this._areMiscDirty = true;
  34809. this._isDirty = true;
  34810. };
  34811. /**
  34812. * Rebuilds the material defines
  34813. */
  34814. MaterialDefines.prototype.rebuild = function () {
  34815. if (this._keys) {
  34816. delete this._keys;
  34817. }
  34818. this._keys = [];
  34819. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34820. var key = _a[_i];
  34821. if (key[0] === "_") {
  34822. continue;
  34823. }
  34824. this._keys.push(key);
  34825. }
  34826. };
  34827. /**
  34828. * Specifies if two material defines are equal
  34829. * @param other - A material define instance to compare to
  34830. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34831. */
  34832. MaterialDefines.prototype.isEqual = function (other) {
  34833. if (this._keys.length !== other._keys.length) {
  34834. return false;
  34835. }
  34836. for (var index = 0; index < this._keys.length; index++) {
  34837. var prop = this._keys[index];
  34838. if (this[prop] !== other[prop]) {
  34839. return false;
  34840. }
  34841. }
  34842. return true;
  34843. };
  34844. /**
  34845. * Clones this instance's defines to another instance
  34846. * @param other - material defines to clone values to
  34847. */
  34848. MaterialDefines.prototype.cloneTo = function (other) {
  34849. if (this._keys.length !== other._keys.length) {
  34850. other._keys = this._keys.slice(0);
  34851. }
  34852. for (var index = 0; index < this._keys.length; index++) {
  34853. var prop = this._keys[index];
  34854. other[prop] = this[prop];
  34855. }
  34856. };
  34857. /**
  34858. * Resets the material define values
  34859. */
  34860. MaterialDefines.prototype.reset = function () {
  34861. for (var index = 0; index < this._keys.length; index++) {
  34862. var prop = this._keys[index];
  34863. var type = typeof this[prop];
  34864. switch (type) {
  34865. case "number":
  34866. this[prop] = 0;
  34867. break;
  34868. case "string":
  34869. this[prop] = "";
  34870. break;
  34871. default:
  34872. this[prop] = false;
  34873. break;
  34874. }
  34875. }
  34876. };
  34877. /**
  34878. * Converts the material define values to a string
  34879. * @returns - String of material define information
  34880. */
  34881. MaterialDefines.prototype.toString = function () {
  34882. var result = "";
  34883. for (var index = 0; index < this._keys.length; index++) {
  34884. var prop = this._keys[index];
  34885. var value = this[prop];
  34886. var type = typeof value;
  34887. switch (type) {
  34888. case "number":
  34889. case "string":
  34890. result += "#define " + prop + " " + value + "\n";
  34891. break;
  34892. default:
  34893. if (value) {
  34894. result += "#define " + prop + "\n";
  34895. }
  34896. break;
  34897. }
  34898. }
  34899. return result;
  34900. };
  34901. return MaterialDefines;
  34902. }());
  34903. BABYLON.MaterialDefines = MaterialDefines;
  34904. /**
  34905. * Base class for the main features of a material in Babylon.js
  34906. */
  34907. var Material = /** @class */ (function () {
  34908. /**
  34909. * Creates a material instance
  34910. * @param name defines the name of the material
  34911. * @param scene defines the scene to reference
  34912. * @param doNotAdd specifies if the material should be added to the scene
  34913. */
  34914. function Material(name, scene, doNotAdd) {
  34915. /**
  34916. * Specifies if the ready state should be checked on each call
  34917. */
  34918. this.checkReadyOnEveryCall = false;
  34919. /**
  34920. * Specifies if the ready state should be checked once
  34921. */
  34922. this.checkReadyOnlyOnce = false;
  34923. /**
  34924. * The state of the material
  34925. */
  34926. this.state = "";
  34927. /**
  34928. * The alpha value of the material
  34929. */
  34930. this._alpha = 1.0;
  34931. /**
  34932. * Specifies if back face culling is enabled
  34933. */
  34934. this._backFaceCulling = true;
  34935. /**
  34936. * Specifies if the material should be serialized
  34937. */
  34938. this.doNotSerialize = false;
  34939. /**
  34940. * Specifies if the effect should be stored on sub meshes
  34941. */
  34942. this.storeEffectOnSubMeshes = false;
  34943. /**
  34944. * An event triggered when the material is disposed
  34945. */
  34946. this.onDisposeObservable = new BABYLON.Observable();
  34947. /**
  34948. * An event triggered when the material is bound
  34949. */
  34950. this.onBindObservable = new BABYLON.Observable();
  34951. /**
  34952. * An event triggered when the material is unbound
  34953. */
  34954. this.onUnBindObservable = new BABYLON.Observable();
  34955. /**
  34956. * Stores the value of the alpha mode
  34957. */
  34958. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34959. /**
  34960. * Stores the state of the need depth pre-pass value
  34961. */
  34962. this._needDepthPrePass = false;
  34963. /**
  34964. * Specifies if depth writing should be disabled
  34965. */
  34966. this.disableDepthWrite = false;
  34967. /**
  34968. * Specifies if depth writing should be forced
  34969. */
  34970. this.forceDepthWrite = false;
  34971. /**
  34972. * Specifies if there should be a separate pass for culling
  34973. */
  34974. this.separateCullingPass = false;
  34975. /**
  34976. * Stores the state specifing if fog should be enabled
  34977. */
  34978. this._fogEnabled = true;
  34979. /**
  34980. * Stores the size of points
  34981. */
  34982. this.pointSize = 1.0;
  34983. /**
  34984. * Stores the z offset value
  34985. */
  34986. this.zOffset = 0;
  34987. /**
  34988. * Specifies if the material was previously ready
  34989. */
  34990. this._wasPreviouslyReady = false;
  34991. /**
  34992. * Stores the fill mode state
  34993. */
  34994. this._fillMode = Material.TriangleFillMode;
  34995. this.name = name;
  34996. this.id = name || BABYLON.Tools.RandomId();
  34997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34998. this.uniqueId = this._scene.getUniqueId();
  34999. if (this._scene.useRightHandedSystem) {
  35000. this.sideOrientation = Material.ClockWiseSideOrientation;
  35001. }
  35002. else {
  35003. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35004. }
  35005. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35006. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35007. if (!doNotAdd) {
  35008. this._scene.materials.push(this);
  35009. }
  35010. }
  35011. Object.defineProperty(Material, "TriangleFillMode", {
  35012. /**
  35013. * Returns the triangle fill mode
  35014. */
  35015. get: function () {
  35016. return Material._TriangleFillMode;
  35017. },
  35018. enumerable: true,
  35019. configurable: true
  35020. });
  35021. Object.defineProperty(Material, "WireFrameFillMode", {
  35022. /**
  35023. * Returns the wireframe mode
  35024. */
  35025. get: function () {
  35026. return Material._WireFrameFillMode;
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. Object.defineProperty(Material, "PointFillMode", {
  35032. /**
  35033. * Returns the point fill mode
  35034. */
  35035. get: function () {
  35036. return Material._PointFillMode;
  35037. },
  35038. enumerable: true,
  35039. configurable: true
  35040. });
  35041. Object.defineProperty(Material, "PointListDrawMode", {
  35042. /**
  35043. * Returns the point list draw mode
  35044. */
  35045. get: function () {
  35046. return Material._PointListDrawMode;
  35047. },
  35048. enumerable: true,
  35049. configurable: true
  35050. });
  35051. Object.defineProperty(Material, "LineListDrawMode", {
  35052. /**
  35053. * Returns the line list draw mode
  35054. */
  35055. get: function () {
  35056. return Material._LineListDrawMode;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. Object.defineProperty(Material, "LineLoopDrawMode", {
  35062. /**
  35063. * Returns the line loop draw mode
  35064. */
  35065. get: function () {
  35066. return Material._LineLoopDrawMode;
  35067. },
  35068. enumerable: true,
  35069. configurable: true
  35070. });
  35071. Object.defineProperty(Material, "LineStripDrawMode", {
  35072. /**
  35073. * Returns the line strip draw mode
  35074. */
  35075. get: function () {
  35076. return Material._LineStripDrawMode;
  35077. },
  35078. enumerable: true,
  35079. configurable: true
  35080. });
  35081. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35082. /**
  35083. * Returns the triangle strip draw mode
  35084. */
  35085. get: function () {
  35086. return Material._TriangleStripDrawMode;
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35092. /**
  35093. * Returns the triangle fan draw mode
  35094. */
  35095. get: function () {
  35096. return Material._TriangleFanDrawMode;
  35097. },
  35098. enumerable: true,
  35099. configurable: true
  35100. });
  35101. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35102. /**
  35103. * Returns the clock-wise side orientation
  35104. */
  35105. get: function () {
  35106. return Material._ClockWiseSideOrientation;
  35107. },
  35108. enumerable: true,
  35109. configurable: true
  35110. });
  35111. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35112. /**
  35113. * Returns the counter clock-wise side orientation
  35114. */
  35115. get: function () {
  35116. return Material._CounterClockWiseSideOrientation;
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. Object.defineProperty(Material, "TextureDirtyFlag", {
  35122. /**
  35123. * Returns the dirty texture flag value
  35124. */
  35125. get: function () {
  35126. return Material._TextureDirtyFlag;
  35127. },
  35128. enumerable: true,
  35129. configurable: true
  35130. });
  35131. Object.defineProperty(Material, "LightDirtyFlag", {
  35132. /**
  35133. * Returns the dirty light flag value
  35134. */
  35135. get: function () {
  35136. return Material._LightDirtyFlag;
  35137. },
  35138. enumerable: true,
  35139. configurable: true
  35140. });
  35141. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35142. /**
  35143. * Returns the dirty fresnel flag value
  35144. */
  35145. get: function () {
  35146. return Material._FresnelDirtyFlag;
  35147. },
  35148. enumerable: true,
  35149. configurable: true
  35150. });
  35151. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35152. /**
  35153. * Returns the dirty attributes flag value
  35154. */
  35155. get: function () {
  35156. return Material._AttributesDirtyFlag;
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(Material, "MiscDirtyFlag", {
  35162. /**
  35163. * Returns the dirty misc flag value
  35164. */
  35165. get: function () {
  35166. return Material._MiscDirtyFlag;
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. Object.defineProperty(Material.prototype, "alpha", {
  35172. /**
  35173. * Gets the alpha value of the material
  35174. */
  35175. get: function () {
  35176. return this._alpha;
  35177. },
  35178. /**
  35179. * Sets the alpha value of the material
  35180. */
  35181. set: function (value) {
  35182. if (this._alpha === value) {
  35183. return;
  35184. }
  35185. this._alpha = value;
  35186. this.markAsDirty(Material.MiscDirtyFlag);
  35187. },
  35188. enumerable: true,
  35189. configurable: true
  35190. });
  35191. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35192. /**
  35193. * Gets the back-face culling state
  35194. */
  35195. get: function () {
  35196. return this._backFaceCulling;
  35197. },
  35198. /**
  35199. * Sets the back-face culling state
  35200. */
  35201. set: function (value) {
  35202. if (this._backFaceCulling === value) {
  35203. return;
  35204. }
  35205. this._backFaceCulling = value;
  35206. this.markAsDirty(Material.TextureDirtyFlag);
  35207. },
  35208. enumerable: true,
  35209. configurable: true
  35210. });
  35211. Object.defineProperty(Material.prototype, "onDispose", {
  35212. /**
  35213. * Called during a dispose event
  35214. */
  35215. set: function (callback) {
  35216. if (this._onDisposeObserver) {
  35217. this.onDisposeObservable.remove(this._onDisposeObserver);
  35218. }
  35219. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35220. },
  35221. enumerable: true,
  35222. configurable: true
  35223. });
  35224. Object.defineProperty(Material.prototype, "onBind", {
  35225. /**
  35226. * Called during a bind event
  35227. */
  35228. set: function (callback) {
  35229. if (this._onBindObserver) {
  35230. this.onBindObservable.remove(this._onBindObserver);
  35231. }
  35232. this._onBindObserver = this.onBindObservable.add(callback);
  35233. },
  35234. enumerable: true,
  35235. configurable: true
  35236. });
  35237. Object.defineProperty(Material.prototype, "alphaMode", {
  35238. /**
  35239. * Gets the value of the alpha mode
  35240. */
  35241. get: function () {
  35242. return this._alphaMode;
  35243. },
  35244. /**
  35245. * Sets the value of the alpha mode.
  35246. *
  35247. * | Value | Type | Description |
  35248. * | --- | --- | --- |
  35249. * | 0 | ALPHA_DISABLE | |
  35250. * | 1 | ALPHA_ADD | |
  35251. * | 2 | ALPHA_COMBINE | |
  35252. * | 3 | ALPHA_SUBTRACT | |
  35253. * | 4 | ALPHA_MULTIPLY | |
  35254. * | 5 | ALPHA_MAXIMIZED | |
  35255. * | 6 | ALPHA_ONEONE | |
  35256. * | 7 | ALPHA_PREMULTIPLIED | |
  35257. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35258. * | 9 | ALPHA_INTERPOLATE | |
  35259. * | 10 | ALPHA_SCREENMODE | |
  35260. *
  35261. */
  35262. set: function (value) {
  35263. if (this._alphaMode === value) {
  35264. return;
  35265. }
  35266. this._alphaMode = value;
  35267. this.markAsDirty(Material.TextureDirtyFlag);
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35273. /**
  35274. * Gets the depth pre-pass value
  35275. */
  35276. get: function () {
  35277. return this._needDepthPrePass;
  35278. },
  35279. /**
  35280. * Sets the need depth pre-pass value
  35281. */
  35282. set: function (value) {
  35283. if (this._needDepthPrePass === value) {
  35284. return;
  35285. }
  35286. this._needDepthPrePass = value;
  35287. if (this._needDepthPrePass) {
  35288. this.checkReadyOnEveryCall = true;
  35289. }
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. Object.defineProperty(Material.prototype, "fogEnabled", {
  35295. /**
  35296. * Gets the value of the fog enabled state
  35297. */
  35298. get: function () {
  35299. return this._fogEnabled;
  35300. },
  35301. /**
  35302. * Sets the state for enabling fog
  35303. */
  35304. set: function (value) {
  35305. if (this._fogEnabled === value) {
  35306. return;
  35307. }
  35308. this._fogEnabled = value;
  35309. this.markAsDirty(Material.MiscDirtyFlag);
  35310. },
  35311. enumerable: true,
  35312. configurable: true
  35313. });
  35314. Object.defineProperty(Material.prototype, "wireframe", {
  35315. /**
  35316. * Gets a value specifying if wireframe mode is enabled
  35317. */
  35318. get: function () {
  35319. switch (this._fillMode) {
  35320. case Material.WireFrameFillMode:
  35321. case Material.LineListDrawMode:
  35322. case Material.LineLoopDrawMode:
  35323. case Material.LineStripDrawMode:
  35324. return true;
  35325. }
  35326. return this._scene.forceWireframe;
  35327. },
  35328. /**
  35329. * Sets the state of wireframe mode
  35330. */
  35331. set: function (value) {
  35332. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35333. },
  35334. enumerable: true,
  35335. configurable: true
  35336. });
  35337. Object.defineProperty(Material.prototype, "pointsCloud", {
  35338. /**
  35339. * Gets the value specifying if point clouds are enabled
  35340. */
  35341. get: function () {
  35342. switch (this._fillMode) {
  35343. case Material.PointFillMode:
  35344. case Material.PointListDrawMode:
  35345. return true;
  35346. }
  35347. return this._scene.forcePointsCloud;
  35348. },
  35349. /**
  35350. * Sets the state of point cloud mode
  35351. */
  35352. set: function (value) {
  35353. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(Material.prototype, "fillMode", {
  35359. /**
  35360. * Gets the material fill mode
  35361. */
  35362. get: function () {
  35363. return this._fillMode;
  35364. },
  35365. /**
  35366. * Sets the material fill mode
  35367. */
  35368. set: function (value) {
  35369. if (this._fillMode === value) {
  35370. return;
  35371. }
  35372. this._fillMode = value;
  35373. this.markAsDirty(Material.MiscDirtyFlag);
  35374. },
  35375. enumerable: true,
  35376. configurable: true
  35377. });
  35378. /**
  35379. * Returns a string representation of the current material
  35380. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35381. * @returns a string with material information
  35382. */
  35383. Material.prototype.toString = function (fullDetails) {
  35384. var ret = "Name: " + this.name;
  35385. if (fullDetails) {
  35386. }
  35387. return ret;
  35388. };
  35389. /**
  35390. * Gets the class name of the material
  35391. * @returns a string with the class name of the material
  35392. */
  35393. Material.prototype.getClassName = function () {
  35394. return "Material";
  35395. };
  35396. Object.defineProperty(Material.prototype, "isFrozen", {
  35397. /**
  35398. * Specifies if updates for the material been locked
  35399. */
  35400. get: function () {
  35401. return this.checkReadyOnlyOnce;
  35402. },
  35403. enumerable: true,
  35404. configurable: true
  35405. });
  35406. /**
  35407. * Locks updates for the material
  35408. */
  35409. Material.prototype.freeze = function () {
  35410. this.checkReadyOnlyOnce = true;
  35411. };
  35412. /**
  35413. * Unlocks updates for the material
  35414. */
  35415. Material.prototype.unfreeze = function () {
  35416. this.checkReadyOnlyOnce = false;
  35417. };
  35418. /**
  35419. * Specifies if the material is ready to be used
  35420. * @param mesh defines the mesh to check
  35421. * @param useInstances specifies if instances should be used
  35422. * @returns a boolean indicating if the material is ready to be used
  35423. */
  35424. Material.prototype.isReady = function (mesh, useInstances) {
  35425. return true;
  35426. };
  35427. /**
  35428. * Specifies that the submesh is ready to be used
  35429. * @param mesh defines the mesh to check
  35430. * @param subMesh defines which submesh to check
  35431. * @param useInstances specifies that instances should be used
  35432. * @returns a boolean indicating that the submesh is ready or not
  35433. */
  35434. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35435. return false;
  35436. };
  35437. /**
  35438. * Returns the material effect
  35439. * @returns the effect associated with the material
  35440. */
  35441. Material.prototype.getEffect = function () {
  35442. return this._effect;
  35443. };
  35444. /**
  35445. * Returns the current scene
  35446. * @returns a Scene
  35447. */
  35448. Material.prototype.getScene = function () {
  35449. return this._scene;
  35450. };
  35451. /**
  35452. * Specifies if the material will require alpha blending
  35453. * @returns a boolean specifying if alpha blending is needed
  35454. */
  35455. Material.prototype.needAlphaBlending = function () {
  35456. return (this.alpha < 1.0);
  35457. };
  35458. /**
  35459. * Specifies if the mesh will require alpha blending
  35460. * @param mesh defines the mesh to check
  35461. * @returns a boolean specifying if alpha blending is needed for the mesh
  35462. */
  35463. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35464. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35465. };
  35466. /**
  35467. * Specifies if this material should be rendered in alpha test mode
  35468. * @returns a boolean specifying if an alpha test is needed.
  35469. */
  35470. Material.prototype.needAlphaTesting = function () {
  35471. return false;
  35472. };
  35473. /**
  35474. * Gets the texture used for the alpha test
  35475. * @returns the texture to use for alpha testing
  35476. */
  35477. Material.prototype.getAlphaTestTexture = function () {
  35478. return null;
  35479. };
  35480. /**
  35481. * Marks the material to indicate that it needs to be re-calculated
  35482. */
  35483. Material.prototype.markDirty = function () {
  35484. this._wasPreviouslyReady = false;
  35485. };
  35486. /** @hidden */
  35487. Material.prototype._preBind = function (effect, overrideOrientation) {
  35488. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35489. var engine = this._scene.getEngine();
  35490. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35491. var reverse = orientation === Material.ClockWiseSideOrientation;
  35492. engine.enableEffect(effect ? effect : this._effect);
  35493. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35494. return reverse;
  35495. };
  35496. /**
  35497. * Binds the material to the mesh
  35498. * @param world defines the world transformation matrix
  35499. * @param mesh defines the mesh to bind the material to
  35500. */
  35501. Material.prototype.bind = function (world, mesh) {
  35502. };
  35503. /**
  35504. * Binds the submesh to the material
  35505. * @param world defines the world transformation matrix
  35506. * @param mesh defines the mesh containing the submesh
  35507. * @param subMesh defines the submesh to bind the material to
  35508. */
  35509. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35510. };
  35511. /**
  35512. * Binds the world matrix to the material
  35513. * @param world defines the world transformation matrix
  35514. */
  35515. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35516. };
  35517. /**
  35518. * Binds the scene's uniform buffer to the effect.
  35519. * @param effect defines the effect to bind to the scene uniform buffer
  35520. * @param sceneUbo defines the uniform buffer storing scene data
  35521. */
  35522. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35523. sceneUbo.bindToEffect(effect, "Scene");
  35524. };
  35525. /**
  35526. * Binds the view matrix to the effect
  35527. * @param effect defines the effect to bind the view matrix to
  35528. */
  35529. Material.prototype.bindView = function (effect) {
  35530. if (!this._useUBO) {
  35531. effect.setMatrix("view", this.getScene().getViewMatrix());
  35532. }
  35533. else {
  35534. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35535. }
  35536. };
  35537. /**
  35538. * Binds the view projection matrix to the effect
  35539. * @param effect defines the effect to bind the view projection matrix to
  35540. */
  35541. Material.prototype.bindViewProjection = function (effect) {
  35542. if (!this._useUBO) {
  35543. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35544. }
  35545. else {
  35546. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35547. }
  35548. };
  35549. /**
  35550. * Specifies if material alpha testing should be turned on for the mesh
  35551. * @param mesh defines the mesh to check
  35552. */
  35553. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35554. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35555. };
  35556. /**
  35557. * Processes to execute after binding the material to a mesh
  35558. * @param mesh defines the rendered mesh
  35559. */
  35560. Material.prototype._afterBind = function (mesh) {
  35561. this._scene._cachedMaterial = this;
  35562. if (mesh) {
  35563. this._scene._cachedVisibility = mesh.visibility;
  35564. }
  35565. else {
  35566. this._scene._cachedVisibility = 1;
  35567. }
  35568. if (mesh) {
  35569. this.onBindObservable.notifyObservers(mesh);
  35570. }
  35571. if (this.disableDepthWrite) {
  35572. var engine = this._scene.getEngine();
  35573. this._cachedDepthWriteState = engine.getDepthWrite();
  35574. engine.setDepthWrite(false);
  35575. }
  35576. };
  35577. /**
  35578. * Unbinds the material from the mesh
  35579. */
  35580. Material.prototype.unbind = function () {
  35581. this.onUnBindObservable.notifyObservers(this);
  35582. if (this.disableDepthWrite) {
  35583. var engine = this._scene.getEngine();
  35584. engine.setDepthWrite(this._cachedDepthWriteState);
  35585. }
  35586. };
  35587. /**
  35588. * Gets the active textures from the material
  35589. * @returns an array of textures
  35590. */
  35591. Material.prototype.getActiveTextures = function () {
  35592. return [];
  35593. };
  35594. /**
  35595. * Specifies if the material uses a texture
  35596. * @param texture defines the texture to check against the material
  35597. * @returns a boolean specifying if the material uses the texture
  35598. */
  35599. Material.prototype.hasTexture = function (texture) {
  35600. return false;
  35601. };
  35602. /**
  35603. * Makes a duplicate of the material, and gives it a new name
  35604. * @param name defines the new name for the duplicated material
  35605. * @returns the cloned material
  35606. */
  35607. Material.prototype.clone = function (name) {
  35608. return null;
  35609. };
  35610. /**
  35611. * Gets the meshes bound to the material
  35612. * @returns an array of meshes bound to the material
  35613. */
  35614. Material.prototype.getBindedMeshes = function () {
  35615. var result = new Array();
  35616. for (var index = 0; index < this._scene.meshes.length; index++) {
  35617. var mesh = this._scene.meshes[index];
  35618. if (mesh.material === this) {
  35619. result.push(mesh);
  35620. }
  35621. }
  35622. return result;
  35623. };
  35624. /**
  35625. * Force shader compilation
  35626. * @param mesh defines the mesh associated with this material
  35627. * @param onCompiled defines a function to execute once the material is compiled
  35628. * @param options defines the options to configure the compilation
  35629. */
  35630. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35631. var _this = this;
  35632. var localOptions = __assign({ clipPlane: false }, options);
  35633. var subMesh = new BABYLON.BaseSubMesh();
  35634. var scene = this.getScene();
  35635. var checkReady = function () {
  35636. if (!_this._scene || !_this._scene.getEngine()) {
  35637. return;
  35638. }
  35639. if (subMesh._materialDefines) {
  35640. subMesh._materialDefines._renderId = -1;
  35641. }
  35642. var clipPlaneState = scene.clipPlane;
  35643. if (localOptions.clipPlane) {
  35644. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35645. }
  35646. if (_this.storeEffectOnSubMeshes) {
  35647. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35648. if (onCompiled) {
  35649. onCompiled(_this);
  35650. }
  35651. }
  35652. else {
  35653. setTimeout(checkReady, 16);
  35654. }
  35655. }
  35656. else {
  35657. if (_this.isReady(mesh)) {
  35658. if (onCompiled) {
  35659. onCompiled(_this);
  35660. }
  35661. }
  35662. else {
  35663. setTimeout(checkReady, 16);
  35664. }
  35665. }
  35666. if (localOptions.clipPlane) {
  35667. scene.clipPlane = clipPlaneState;
  35668. }
  35669. };
  35670. checkReady();
  35671. };
  35672. /**
  35673. * Force shader compilation
  35674. * @param mesh defines the mesh that will use this material
  35675. * @param options defines additional options for compiling the shaders
  35676. * @returns a promise that resolves when the compilation completes
  35677. */
  35678. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35679. var _this = this;
  35680. return new Promise(function (resolve) {
  35681. _this.forceCompilation(mesh, function () {
  35682. resolve();
  35683. }, options);
  35684. });
  35685. };
  35686. /**
  35687. * Marks a define in the material to indicate that it needs to be re-computed
  35688. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35689. */
  35690. Material.prototype.markAsDirty = function (flag) {
  35691. if (flag & Material.TextureDirtyFlag) {
  35692. this._markAllSubMeshesAsTexturesDirty();
  35693. }
  35694. if (flag & Material.LightDirtyFlag) {
  35695. this._markAllSubMeshesAsLightsDirty();
  35696. }
  35697. if (flag & Material.FresnelDirtyFlag) {
  35698. this._markAllSubMeshesAsFresnelDirty();
  35699. }
  35700. if (flag & Material.AttributesDirtyFlag) {
  35701. this._markAllSubMeshesAsAttributesDirty();
  35702. }
  35703. if (flag & Material.MiscDirtyFlag) {
  35704. this._markAllSubMeshesAsMiscDirty();
  35705. }
  35706. this.getScene().resetCachedMaterial();
  35707. };
  35708. /**
  35709. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35710. * @param func defines a function which checks material defines against the submeshes
  35711. */
  35712. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35713. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35714. var mesh = _a[_i];
  35715. if (!mesh.subMeshes) {
  35716. continue;
  35717. }
  35718. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35719. var subMesh = _c[_b];
  35720. if (subMesh.getMaterial() !== this) {
  35721. continue;
  35722. }
  35723. if (!subMesh._materialDefines) {
  35724. continue;
  35725. }
  35726. func(subMesh._materialDefines);
  35727. }
  35728. }
  35729. };
  35730. /**
  35731. * Indicates that image processing needs to be re-calculated for all submeshes
  35732. */
  35733. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35734. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35735. };
  35736. /**
  35737. * Indicates that textures need to be re-calculated for all submeshes
  35738. */
  35739. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35740. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35741. };
  35742. /**
  35743. * Indicates that fresnel needs to be re-calculated for all submeshes
  35744. */
  35745. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35746. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35747. };
  35748. /**
  35749. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35750. */
  35751. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35752. this._markAllSubMeshesAsDirty(function (defines) {
  35753. defines.markAsFresnelDirty();
  35754. defines.markAsMiscDirty();
  35755. });
  35756. };
  35757. /**
  35758. * Indicates that lights need to be re-calculated for all submeshes
  35759. */
  35760. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35761. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35762. };
  35763. /**
  35764. * Indicates that attributes need to be re-calculated for all submeshes
  35765. */
  35766. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35767. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35768. };
  35769. /**
  35770. * Indicates that misc needs to be re-calculated for all submeshes
  35771. */
  35772. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35773. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35774. };
  35775. /**
  35776. * Indicates that textures and misc need to be re-calculated for all submeshes
  35777. */
  35778. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35779. this._markAllSubMeshesAsDirty(function (defines) {
  35780. defines.markAsTexturesDirty();
  35781. defines.markAsMiscDirty();
  35782. });
  35783. };
  35784. /**
  35785. * Disposes the material
  35786. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35787. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35788. */
  35789. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35790. // Animations
  35791. this.getScene().stopAnimation(this);
  35792. this.getScene().freeProcessedMaterials();
  35793. // Remove from scene
  35794. var index = this._scene.materials.indexOf(this);
  35795. if (index >= 0) {
  35796. this._scene.materials.splice(index, 1);
  35797. }
  35798. // Remove from meshes
  35799. for (index = 0; index < this._scene.meshes.length; index++) {
  35800. var mesh = this._scene.meshes[index];
  35801. if (mesh.material === this) {
  35802. mesh.material = null;
  35803. if (mesh.geometry) {
  35804. var geometry = (mesh.geometry);
  35805. if (this.storeEffectOnSubMeshes) {
  35806. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35807. var subMesh = _a[_i];
  35808. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35809. if (forceDisposeEffect && subMesh._materialEffect) {
  35810. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35811. }
  35812. }
  35813. }
  35814. else {
  35815. geometry._releaseVertexArrayObject(this._effect);
  35816. }
  35817. }
  35818. }
  35819. }
  35820. this._uniformBuffer.dispose();
  35821. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35822. if (forceDisposeEffect && this._effect) {
  35823. if (!this.storeEffectOnSubMeshes) {
  35824. this._scene.getEngine()._releaseEffect(this._effect);
  35825. }
  35826. this._effect = null;
  35827. }
  35828. // Callback
  35829. this.onDisposeObservable.notifyObservers(this);
  35830. this.onDisposeObservable.clear();
  35831. this.onBindObservable.clear();
  35832. this.onUnBindObservable.clear();
  35833. };
  35834. /**
  35835. * Serializes this material
  35836. * @returns the serialized material object
  35837. */
  35838. Material.prototype.serialize = function () {
  35839. return BABYLON.SerializationHelper.Serialize(this);
  35840. };
  35841. /**
  35842. * Creates a MultiMaterial from parsed MultiMaterial data.
  35843. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35844. * @param scene defines the hosting scene
  35845. * @returns a new MultiMaterial
  35846. */
  35847. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35848. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35849. multiMaterial.id = parsedMultiMaterial.id;
  35850. if (BABYLON.Tags) {
  35851. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35852. }
  35853. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35854. var subMatId = parsedMultiMaterial.materials[matIndex];
  35855. if (subMatId) {
  35856. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35857. }
  35858. else {
  35859. multiMaterial.subMaterials.push(null);
  35860. }
  35861. }
  35862. return multiMaterial;
  35863. };
  35864. /**
  35865. * Creates a material from parsed material data
  35866. * @param parsedMaterial defines parsed material data
  35867. * @param scene defines the hosting scene
  35868. * @param rootUrl defines the root URL to use to load textures
  35869. * @returns a new material
  35870. */
  35871. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35872. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35873. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35874. }
  35875. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35876. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35877. if (!BABYLON.LegacyPBRMaterial) {
  35878. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35879. return;
  35880. }
  35881. }
  35882. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35883. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35884. };
  35885. // Triangle views
  35886. Material._TriangleFillMode = 0;
  35887. Material._WireFrameFillMode = 1;
  35888. Material._PointFillMode = 2;
  35889. // Draw modes
  35890. Material._PointListDrawMode = 3;
  35891. Material._LineListDrawMode = 4;
  35892. Material._LineLoopDrawMode = 5;
  35893. Material._LineStripDrawMode = 6;
  35894. Material._TriangleStripDrawMode = 7;
  35895. Material._TriangleFanDrawMode = 8;
  35896. /**
  35897. * Stores the clock-wise side orientation
  35898. */
  35899. Material._ClockWiseSideOrientation = 0;
  35900. /**
  35901. * Stores the counter clock-wise side orientation
  35902. */
  35903. Material._CounterClockWiseSideOrientation = 1;
  35904. /**
  35905. * The dirty texture flag value
  35906. */
  35907. Material._TextureDirtyFlag = 1;
  35908. /**
  35909. * The dirty light flag value
  35910. */
  35911. Material._LightDirtyFlag = 2;
  35912. /**
  35913. * The dirty fresnel flag value
  35914. */
  35915. Material._FresnelDirtyFlag = 4;
  35916. /**
  35917. * The dirty attribute flag value
  35918. */
  35919. Material._AttributesDirtyFlag = 8;
  35920. /**
  35921. * The dirty misc flag value
  35922. */
  35923. Material._MiscDirtyFlag = 16;
  35924. __decorate([
  35925. BABYLON.serialize()
  35926. ], Material.prototype, "id", void 0);
  35927. __decorate([
  35928. BABYLON.serialize()
  35929. ], Material.prototype, "uniqueId", void 0);
  35930. __decorate([
  35931. BABYLON.serialize()
  35932. ], Material.prototype, "name", void 0);
  35933. __decorate([
  35934. BABYLON.serialize()
  35935. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35936. __decorate([
  35937. BABYLON.serialize()
  35938. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35939. __decorate([
  35940. BABYLON.serialize()
  35941. ], Material.prototype, "state", void 0);
  35942. __decorate([
  35943. BABYLON.serialize("alpha")
  35944. ], Material.prototype, "_alpha", void 0);
  35945. __decorate([
  35946. BABYLON.serialize("backFaceCulling")
  35947. ], Material.prototype, "_backFaceCulling", void 0);
  35948. __decorate([
  35949. BABYLON.serialize()
  35950. ], Material.prototype, "sideOrientation", void 0);
  35951. __decorate([
  35952. BABYLON.serialize("alphaMode")
  35953. ], Material.prototype, "_alphaMode", void 0);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], Material.prototype, "_needDepthPrePass", void 0);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], Material.prototype, "disableDepthWrite", void 0);
  35960. __decorate([
  35961. BABYLON.serialize()
  35962. ], Material.prototype, "forceDepthWrite", void 0);
  35963. __decorate([
  35964. BABYLON.serialize()
  35965. ], Material.prototype, "separateCullingPass", void 0);
  35966. __decorate([
  35967. BABYLON.serialize("fogEnabled")
  35968. ], Material.prototype, "_fogEnabled", void 0);
  35969. __decorate([
  35970. BABYLON.serialize()
  35971. ], Material.prototype, "pointSize", void 0);
  35972. __decorate([
  35973. BABYLON.serialize()
  35974. ], Material.prototype, "zOffset", void 0);
  35975. __decorate([
  35976. BABYLON.serialize()
  35977. ], Material.prototype, "wireframe", null);
  35978. __decorate([
  35979. BABYLON.serialize()
  35980. ], Material.prototype, "pointsCloud", null);
  35981. __decorate([
  35982. BABYLON.serialize()
  35983. ], Material.prototype, "fillMode", null);
  35984. return Material;
  35985. }());
  35986. BABYLON.Material = Material;
  35987. })(BABYLON || (BABYLON = {}));
  35988. //# sourceMappingURL=babylon.material.js.map
  35989. var BABYLON;
  35990. (function (BABYLON) {
  35991. var UniformBuffer = /** @class */ (function () {
  35992. /**
  35993. * Uniform buffer objects.
  35994. *
  35995. * Handles blocks of uniform on the GPU.
  35996. *
  35997. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35998. *
  35999. * For more information, please refer to :
  36000. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36001. */
  36002. function UniformBuffer(engine, data, dynamic) {
  36003. this._engine = engine;
  36004. this._noUBO = !engine.supportsUniformBuffers;
  36005. this._dynamic = dynamic;
  36006. this._data = data || [];
  36007. this._uniformLocations = {};
  36008. this._uniformSizes = {};
  36009. this._uniformLocationPointer = 0;
  36010. this._needSync = false;
  36011. if (this._noUBO) {
  36012. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36013. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36014. this.updateFloat = this._updateFloatForEffect;
  36015. this.updateFloat2 = this._updateFloat2ForEffect;
  36016. this.updateFloat3 = this._updateFloat3ForEffect;
  36017. this.updateFloat4 = this._updateFloat4ForEffect;
  36018. this.updateMatrix = this._updateMatrixForEffect;
  36019. this.updateVector3 = this._updateVector3ForEffect;
  36020. this.updateVector4 = this._updateVector4ForEffect;
  36021. this.updateColor3 = this._updateColor3ForEffect;
  36022. this.updateColor4 = this._updateColor4ForEffect;
  36023. }
  36024. else {
  36025. this._engine._uniformBuffers.push(this);
  36026. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36027. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36028. this.updateFloat = this._updateFloatForUniform;
  36029. this.updateFloat2 = this._updateFloat2ForUniform;
  36030. this.updateFloat3 = this._updateFloat3ForUniform;
  36031. this.updateFloat4 = this._updateFloat4ForUniform;
  36032. this.updateMatrix = this._updateMatrixForUniform;
  36033. this.updateVector3 = this._updateVector3ForUniform;
  36034. this.updateVector4 = this._updateVector4ForUniform;
  36035. this.updateColor3 = this._updateColor3ForUniform;
  36036. this.updateColor4 = this._updateColor4ForUniform;
  36037. }
  36038. }
  36039. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36040. // Properties
  36041. /**
  36042. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36043. * or just falling back on setUniformXXX calls.
  36044. */
  36045. get: function () {
  36046. return !this._noUBO;
  36047. },
  36048. enumerable: true,
  36049. configurable: true
  36050. });
  36051. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36052. /**
  36053. * Indicates if the WebGL underlying uniform buffer is in sync
  36054. * with the javascript cache data.
  36055. */
  36056. get: function () {
  36057. return !this._needSync;
  36058. },
  36059. enumerable: true,
  36060. configurable: true
  36061. });
  36062. /**
  36063. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36064. * Also, a dynamic UniformBuffer will disable cache verification and always
  36065. * update the underlying WebGL uniform buffer to the GPU.
  36066. */
  36067. UniformBuffer.prototype.isDynamic = function () {
  36068. return this._dynamic !== undefined;
  36069. };
  36070. /**
  36071. * The data cache on JS side.
  36072. */
  36073. UniformBuffer.prototype.getData = function () {
  36074. return this._bufferData;
  36075. };
  36076. /**
  36077. * The underlying WebGL Uniform buffer.
  36078. */
  36079. UniformBuffer.prototype.getBuffer = function () {
  36080. return this._buffer;
  36081. };
  36082. /**
  36083. * std140 layout specifies how to align data within an UBO structure.
  36084. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36085. * for specs.
  36086. */
  36087. UniformBuffer.prototype._fillAlignment = function (size) {
  36088. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36089. // and 4x4 matrices
  36090. // TODO : change if other types are used
  36091. var alignment;
  36092. if (size <= 2) {
  36093. alignment = size;
  36094. }
  36095. else {
  36096. alignment = 4;
  36097. }
  36098. if ((this._uniformLocationPointer % alignment) !== 0) {
  36099. var oldPointer = this._uniformLocationPointer;
  36100. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36101. var diff = this._uniformLocationPointer - oldPointer;
  36102. for (var i = 0; i < diff; i++) {
  36103. this._data.push(0);
  36104. }
  36105. }
  36106. };
  36107. /**
  36108. * Adds an uniform in the buffer.
  36109. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36110. * for the layout to be correct !
  36111. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36112. * @param {number|number[]} size Data size, or data directly.
  36113. */
  36114. UniformBuffer.prototype.addUniform = function (name, size) {
  36115. if (this._noUBO) {
  36116. return;
  36117. }
  36118. if (this._uniformLocations[name] !== undefined) {
  36119. // Already existing uniform
  36120. return;
  36121. }
  36122. // This function must be called in the order of the shader layout !
  36123. // size can be the size of the uniform, or data directly
  36124. var data;
  36125. if (size instanceof Array) {
  36126. data = size;
  36127. size = data.length;
  36128. }
  36129. else {
  36130. size = size;
  36131. data = [];
  36132. // Fill with zeros
  36133. for (var i = 0; i < size; i++) {
  36134. data.push(0);
  36135. }
  36136. }
  36137. this._fillAlignment(size);
  36138. this._uniformSizes[name] = size;
  36139. this._uniformLocations[name] = this._uniformLocationPointer;
  36140. this._uniformLocationPointer += size;
  36141. for (var i = 0; i < size; i++) {
  36142. this._data.push(data[i]);
  36143. }
  36144. this._needSync = true;
  36145. };
  36146. /**
  36147. * Wrapper for addUniform.
  36148. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36149. * @param {Matrix} mat A 4x4 matrix.
  36150. */
  36151. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36152. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36153. };
  36154. /**
  36155. * Wrapper for addUniform.
  36156. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36157. * @param {number} x
  36158. * @param {number} y
  36159. */
  36160. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36161. var temp = [x, y];
  36162. this.addUniform(name, temp);
  36163. };
  36164. /**
  36165. * Wrapper for addUniform.
  36166. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36167. * @param {number} x
  36168. * @param {number} y
  36169. * @param {number} z
  36170. */
  36171. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36172. var temp = [x, y, z];
  36173. this.addUniform(name, temp);
  36174. };
  36175. /**
  36176. * Wrapper for addUniform.
  36177. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36178. * @param {Color3} color
  36179. */
  36180. UniformBuffer.prototype.addColor3 = function (name, color) {
  36181. var temp = new Array();
  36182. color.toArray(temp);
  36183. this.addUniform(name, temp);
  36184. };
  36185. /**
  36186. * Wrapper for addUniform.
  36187. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36188. * @param {Color3} color
  36189. * @param {number} alpha
  36190. */
  36191. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36192. var temp = new Array();
  36193. color.toArray(temp);
  36194. temp.push(alpha);
  36195. this.addUniform(name, temp);
  36196. };
  36197. /**
  36198. * Wrapper for addUniform.
  36199. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36200. * @param {Vector3} vector
  36201. */
  36202. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36203. var temp = new Array();
  36204. vector.toArray(temp);
  36205. this.addUniform(name, temp);
  36206. };
  36207. /**
  36208. * Wrapper for addUniform.
  36209. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36210. */
  36211. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36212. this.addUniform(name, 12);
  36213. };
  36214. /**
  36215. * Wrapper for addUniform.
  36216. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36217. */
  36218. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36219. this.addUniform(name, 8);
  36220. };
  36221. /**
  36222. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36223. */
  36224. UniformBuffer.prototype.create = function () {
  36225. if (this._noUBO) {
  36226. return;
  36227. }
  36228. if (this._buffer) {
  36229. return; // nothing to do
  36230. }
  36231. // See spec, alignment must be filled as a vec4
  36232. this._fillAlignment(4);
  36233. this._bufferData = new Float32Array(this._data);
  36234. this._rebuild();
  36235. this._needSync = true;
  36236. };
  36237. UniformBuffer.prototype._rebuild = function () {
  36238. if (this._noUBO) {
  36239. return;
  36240. }
  36241. if (this._dynamic) {
  36242. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36243. }
  36244. else {
  36245. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36246. }
  36247. };
  36248. /**
  36249. * Updates the WebGL Uniform Buffer on the GPU.
  36250. * If the `dynamic` flag is set to true, no cache comparison is done.
  36251. * Otherwise, the buffer will be updated only if the cache differs.
  36252. */
  36253. UniformBuffer.prototype.update = function () {
  36254. if (!this._buffer) {
  36255. this.create();
  36256. return;
  36257. }
  36258. if (!this._dynamic && !this._needSync) {
  36259. return;
  36260. }
  36261. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36262. this._needSync = false;
  36263. };
  36264. /**
  36265. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36266. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36267. * @param {number[]|Float32Array} data Flattened data
  36268. * @param {number} size Size of the data.
  36269. */
  36270. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36271. var location = this._uniformLocations[uniformName];
  36272. if (location === undefined) {
  36273. if (this._buffer) {
  36274. // Cannot add an uniform if the buffer is already created
  36275. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36276. return;
  36277. }
  36278. this.addUniform(uniformName, size);
  36279. location = this._uniformLocations[uniformName];
  36280. }
  36281. if (!this._buffer) {
  36282. this.create();
  36283. }
  36284. if (!this._dynamic) {
  36285. // Cache for static uniform buffers
  36286. var changed = false;
  36287. for (var i = 0; i < size; i++) {
  36288. if (this._bufferData[location + i] !== data[i]) {
  36289. changed = true;
  36290. this._bufferData[location + i] = data[i];
  36291. }
  36292. }
  36293. this._needSync = this._needSync || changed;
  36294. }
  36295. else {
  36296. // No cache for dynamic
  36297. for (var i = 0; i < size; i++) {
  36298. this._bufferData[location + i] = data[i];
  36299. }
  36300. }
  36301. };
  36302. // Update methods
  36303. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36304. // To match std140, matrix must be realigned
  36305. for (var i = 0; i < 3; i++) {
  36306. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36307. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36308. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36309. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36310. }
  36311. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36312. };
  36313. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36314. this._currentEffect.setMatrix3x3(name, matrix);
  36315. };
  36316. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36317. this._currentEffect.setMatrix2x2(name, matrix);
  36318. };
  36319. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36320. // To match std140, matrix must be realigned
  36321. for (var i = 0; i < 2; i++) {
  36322. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36323. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36324. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36325. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36326. }
  36327. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36328. };
  36329. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36330. this._currentEffect.setFloat(name, x);
  36331. };
  36332. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36333. UniformBuffer._tempBuffer[0] = x;
  36334. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36335. };
  36336. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36337. if (suffix === void 0) { suffix = ""; }
  36338. this._currentEffect.setFloat2(name + suffix, x, y);
  36339. };
  36340. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36341. if (suffix === void 0) { suffix = ""; }
  36342. UniformBuffer._tempBuffer[0] = x;
  36343. UniformBuffer._tempBuffer[1] = y;
  36344. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36345. };
  36346. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36347. if (suffix === void 0) { suffix = ""; }
  36348. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36349. };
  36350. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36351. if (suffix === void 0) { suffix = ""; }
  36352. UniformBuffer._tempBuffer[0] = x;
  36353. UniformBuffer._tempBuffer[1] = y;
  36354. UniformBuffer._tempBuffer[2] = z;
  36355. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36356. };
  36357. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36358. if (suffix === void 0) { suffix = ""; }
  36359. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36360. };
  36361. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36362. if (suffix === void 0) { suffix = ""; }
  36363. UniformBuffer._tempBuffer[0] = x;
  36364. UniformBuffer._tempBuffer[1] = y;
  36365. UniformBuffer._tempBuffer[2] = z;
  36366. UniformBuffer._tempBuffer[3] = w;
  36367. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36368. };
  36369. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36370. this._currentEffect.setMatrix(name, mat);
  36371. };
  36372. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36373. this.updateUniform(name, mat.toArray(), 16);
  36374. };
  36375. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36376. this._currentEffect.setVector3(name, vector);
  36377. };
  36378. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36379. vector.toArray(UniformBuffer._tempBuffer);
  36380. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36381. };
  36382. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36383. this._currentEffect.setVector4(name, vector);
  36384. };
  36385. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36386. vector.toArray(UniformBuffer._tempBuffer);
  36387. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36388. };
  36389. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36390. if (suffix === void 0) { suffix = ""; }
  36391. this._currentEffect.setColor3(name + suffix, color);
  36392. };
  36393. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36394. if (suffix === void 0) { suffix = ""; }
  36395. color.toArray(UniformBuffer._tempBuffer);
  36396. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36397. };
  36398. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36399. if (suffix === void 0) { suffix = ""; }
  36400. this._currentEffect.setColor4(name + suffix, color, alpha);
  36401. };
  36402. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36403. if (suffix === void 0) { suffix = ""; }
  36404. color.toArray(UniformBuffer._tempBuffer);
  36405. UniformBuffer._tempBuffer[3] = alpha;
  36406. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36407. };
  36408. /**
  36409. * Sets a sampler uniform on the effect.
  36410. * @param {string} name Name of the sampler.
  36411. * @param {Texture} texture
  36412. */
  36413. UniformBuffer.prototype.setTexture = function (name, texture) {
  36414. this._currentEffect.setTexture(name, texture);
  36415. };
  36416. /**
  36417. * Directly updates the value of the uniform in the cache AND on the GPU.
  36418. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36419. * @param {number[]|Float32Array} data Flattened data
  36420. */
  36421. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36422. this.updateUniform(uniformName, data, data.length);
  36423. this.update();
  36424. };
  36425. /**
  36426. * Binds this uniform buffer to an effect.
  36427. * @param {Effect} effect
  36428. * @param {string} name Name of the uniform block in the shader.
  36429. */
  36430. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36431. this._currentEffect = effect;
  36432. if (this._noUBO || !this._buffer) {
  36433. return;
  36434. }
  36435. effect.bindUniformBuffer(this._buffer, name);
  36436. };
  36437. /**
  36438. * Disposes the uniform buffer.
  36439. */
  36440. UniformBuffer.prototype.dispose = function () {
  36441. if (this._noUBO) {
  36442. return;
  36443. }
  36444. var index = this._engine._uniformBuffers.indexOf(this);
  36445. if (index !== -1) {
  36446. this._engine._uniformBuffers.splice(index, 1);
  36447. }
  36448. if (!this._buffer) {
  36449. return;
  36450. }
  36451. if (this._engine._releaseBuffer(this._buffer)) {
  36452. this._buffer = null;
  36453. }
  36454. };
  36455. // Pool for avoiding memory leaks
  36456. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36457. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36458. return UniformBuffer;
  36459. }());
  36460. BABYLON.UniformBuffer = UniformBuffer;
  36461. })(BABYLON || (BABYLON = {}));
  36462. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36463. var BABYLON;
  36464. (function (BABYLON) {
  36465. /**
  36466. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36467. */
  36468. var VertexData = /** @class */ (function () {
  36469. function VertexData() {
  36470. }
  36471. /**
  36472. * Uses the passed data array to set the set the values for the specified kind of data
  36473. * @param data a linear array of floating numbers
  36474. * @param kind the type of data that is being set, eg positions, colors etc
  36475. */
  36476. VertexData.prototype.set = function (data, kind) {
  36477. switch (kind) {
  36478. case BABYLON.VertexBuffer.PositionKind:
  36479. this.positions = data;
  36480. break;
  36481. case BABYLON.VertexBuffer.NormalKind:
  36482. this.normals = data;
  36483. break;
  36484. case BABYLON.VertexBuffer.TangentKind:
  36485. this.tangents = data;
  36486. break;
  36487. case BABYLON.VertexBuffer.UVKind:
  36488. this.uvs = data;
  36489. break;
  36490. case BABYLON.VertexBuffer.UV2Kind:
  36491. this.uvs2 = data;
  36492. break;
  36493. case BABYLON.VertexBuffer.UV3Kind:
  36494. this.uvs3 = data;
  36495. break;
  36496. case BABYLON.VertexBuffer.UV4Kind:
  36497. this.uvs4 = data;
  36498. break;
  36499. case BABYLON.VertexBuffer.UV5Kind:
  36500. this.uvs5 = data;
  36501. break;
  36502. case BABYLON.VertexBuffer.UV6Kind:
  36503. this.uvs6 = data;
  36504. break;
  36505. case BABYLON.VertexBuffer.ColorKind:
  36506. this.colors = data;
  36507. break;
  36508. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36509. this.matricesIndices = data;
  36510. break;
  36511. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36512. this.matricesWeights = data;
  36513. break;
  36514. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36515. this.matricesIndicesExtra = data;
  36516. break;
  36517. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36518. this.matricesWeightsExtra = data;
  36519. break;
  36520. }
  36521. };
  36522. /**
  36523. * Associates the vertexData to the passed Mesh.
  36524. * Sets it as updatable or not (default `false`)
  36525. * @param mesh the mesh the vertexData is applied to
  36526. * @param updatable when used and having the value true allows new data to update the vertexData
  36527. * @returns the VertexData
  36528. */
  36529. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36530. this._applyTo(mesh, updatable);
  36531. return this;
  36532. };
  36533. /**
  36534. * Associates the vertexData to the passed Geometry.
  36535. * Sets it as updatable or not (default `false`)
  36536. * @param geometry the geometry the vertexData is applied to
  36537. * @param updatable when used and having the value true allows new data to update the vertexData
  36538. * @returns VertexData
  36539. */
  36540. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36541. this._applyTo(geometry, updatable);
  36542. return this;
  36543. };
  36544. /**
  36545. * Updates the associated mesh
  36546. * @param mesh the mesh to be updated
  36547. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36548. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36549. * @returns VertexData
  36550. */
  36551. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36552. this._update(mesh);
  36553. return this;
  36554. };
  36555. /**
  36556. * Updates the associated geometry
  36557. * @param geometry the geometry to be updated
  36558. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36559. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36560. * @returns VertexData.
  36561. */
  36562. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36563. this._update(geometry);
  36564. return this;
  36565. };
  36566. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36567. if (updatable === void 0) { updatable = false; }
  36568. if (this.positions) {
  36569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36570. }
  36571. if (this.normals) {
  36572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36573. }
  36574. if (this.tangents) {
  36575. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36576. }
  36577. if (this.uvs) {
  36578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36579. }
  36580. if (this.uvs2) {
  36581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36582. }
  36583. if (this.uvs3) {
  36584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36585. }
  36586. if (this.uvs4) {
  36587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36588. }
  36589. if (this.uvs5) {
  36590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36591. }
  36592. if (this.uvs6) {
  36593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36594. }
  36595. if (this.colors) {
  36596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36597. }
  36598. if (this.matricesIndices) {
  36599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36600. }
  36601. if (this.matricesWeights) {
  36602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36603. }
  36604. if (this.matricesIndicesExtra) {
  36605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36606. }
  36607. if (this.matricesWeightsExtra) {
  36608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36609. }
  36610. if (this.indices) {
  36611. meshOrGeometry.setIndices(this.indices, null, updatable);
  36612. }
  36613. else {
  36614. meshOrGeometry.setIndices([], null);
  36615. }
  36616. return this;
  36617. };
  36618. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36619. if (this.positions) {
  36620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36621. }
  36622. if (this.normals) {
  36623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36624. }
  36625. if (this.tangents) {
  36626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36627. }
  36628. if (this.uvs) {
  36629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36630. }
  36631. if (this.uvs2) {
  36632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36633. }
  36634. if (this.uvs3) {
  36635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36636. }
  36637. if (this.uvs4) {
  36638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36639. }
  36640. if (this.uvs5) {
  36641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36642. }
  36643. if (this.uvs6) {
  36644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36645. }
  36646. if (this.colors) {
  36647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36648. }
  36649. if (this.matricesIndices) {
  36650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36651. }
  36652. if (this.matricesWeights) {
  36653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36654. }
  36655. if (this.matricesIndicesExtra) {
  36656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36657. }
  36658. if (this.matricesWeightsExtra) {
  36659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36660. }
  36661. if (this.indices) {
  36662. meshOrGeometry.setIndices(this.indices, null);
  36663. }
  36664. return this;
  36665. };
  36666. /**
  36667. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36668. * @param matrix the transforming matrix
  36669. * @returns the VertexData
  36670. */
  36671. VertexData.prototype.transform = function (matrix) {
  36672. var transformed = BABYLON.Vector3.Zero();
  36673. var index;
  36674. if (this.positions) {
  36675. var position = BABYLON.Vector3.Zero();
  36676. for (index = 0; index < this.positions.length; index += 3) {
  36677. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36678. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36679. this.positions[index] = transformed.x;
  36680. this.positions[index + 1] = transformed.y;
  36681. this.positions[index + 2] = transformed.z;
  36682. }
  36683. }
  36684. if (this.normals) {
  36685. var normal = BABYLON.Vector3.Zero();
  36686. for (index = 0; index < this.normals.length; index += 3) {
  36687. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36688. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36689. this.normals[index] = transformed.x;
  36690. this.normals[index + 1] = transformed.y;
  36691. this.normals[index + 2] = transformed.z;
  36692. }
  36693. }
  36694. if (this.tangents) {
  36695. var tangent = BABYLON.Vector4.Zero();
  36696. var tangentTransformed = BABYLON.Vector4.Zero();
  36697. for (index = 0; index < this.tangents.length; index += 4) {
  36698. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36699. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36700. this.tangents[index] = tangentTransformed.x;
  36701. this.tangents[index + 1] = tangentTransformed.y;
  36702. this.tangents[index + 2] = tangentTransformed.z;
  36703. this.tangents[index + 3] = tangentTransformed.w;
  36704. }
  36705. }
  36706. return this;
  36707. };
  36708. /**
  36709. * Merges the passed VertexData into the current one
  36710. * @param other the VertexData to be merged into the current one
  36711. * @returns the modified VertexData
  36712. */
  36713. VertexData.prototype.merge = function (other) {
  36714. this._validate();
  36715. other._validate();
  36716. if (!this.normals !== !other.normals ||
  36717. !this.tangents !== !other.tangents ||
  36718. !this.uvs !== !other.uvs ||
  36719. !this.uvs2 !== !other.uvs2 ||
  36720. !this.uvs3 !== !other.uvs3 ||
  36721. !this.uvs4 !== !other.uvs4 ||
  36722. !this.uvs5 !== !other.uvs5 ||
  36723. !this.uvs6 !== !other.uvs6 ||
  36724. !this.colors !== !other.colors ||
  36725. !this.matricesIndices !== !other.matricesIndices ||
  36726. !this.matricesWeights !== !other.matricesWeights ||
  36727. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36728. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36729. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36730. }
  36731. if (other.indices) {
  36732. if (!this.indices) {
  36733. this.indices = [];
  36734. }
  36735. var offset = this.positions ? this.positions.length / 3 : 0;
  36736. for (var index = 0; index < other.indices.length; index++) {
  36737. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36738. this.indices.push(other.indices[index] + offset);
  36739. }
  36740. }
  36741. this.positions = this._mergeElement(this.positions, other.positions);
  36742. this.normals = this._mergeElement(this.normals, other.normals);
  36743. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36744. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36745. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36746. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36747. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36748. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36749. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36750. this.colors = this._mergeElement(this.colors, other.colors);
  36751. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36752. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36753. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36754. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36755. return this;
  36756. };
  36757. VertexData.prototype._mergeElement = function (source, other) {
  36758. if (!source) {
  36759. return other;
  36760. }
  36761. if (!other) {
  36762. return source;
  36763. }
  36764. var len = other.length + source.length;
  36765. var isSrcTypedArray = source instanceof Float32Array;
  36766. var isOthTypedArray = other instanceof Float32Array;
  36767. // use non-loop method when the source is Float32Array
  36768. if (isSrcTypedArray) {
  36769. var ret32 = new Float32Array(len);
  36770. ret32.set(source);
  36771. ret32.set(other, source.length);
  36772. return ret32;
  36773. // source is number[], when other is also use concat
  36774. }
  36775. else if (!isOthTypedArray) {
  36776. return source.concat(other);
  36777. // source is a number[], but other is a Float32Array, loop required
  36778. }
  36779. else {
  36780. var ret = source.slice(0); // copy source to a separate array
  36781. for (var i = 0, len = other.length; i < len; i++) {
  36782. ret.push(other[i]);
  36783. }
  36784. return ret;
  36785. }
  36786. };
  36787. VertexData.prototype._validate = function () {
  36788. if (!this.positions) {
  36789. throw new Error("Positions are required");
  36790. }
  36791. var getElementCount = function (kind, values) {
  36792. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36793. if ((values.length % stride) !== 0) {
  36794. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36795. }
  36796. return values.length / stride;
  36797. };
  36798. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36799. var validateElementCount = function (kind, values) {
  36800. var elementCount = getElementCount(kind, values);
  36801. if (elementCount !== positionsElementCount) {
  36802. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36803. }
  36804. };
  36805. if (this.normals)
  36806. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36807. if (this.tangents)
  36808. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36809. if (this.uvs)
  36810. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36811. if (this.uvs2)
  36812. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36813. if (this.uvs3)
  36814. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36815. if (this.uvs4)
  36816. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36817. if (this.uvs5)
  36818. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36819. if (this.uvs6)
  36820. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36821. if (this.colors)
  36822. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36823. if (this.matricesIndices)
  36824. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36825. if (this.matricesWeights)
  36826. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36827. if (this.matricesIndicesExtra)
  36828. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36829. if (this.matricesWeightsExtra)
  36830. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36831. };
  36832. /**
  36833. * Serializes the VertexData
  36834. * @returns a serialized object
  36835. */
  36836. VertexData.prototype.serialize = function () {
  36837. var serializationObject = this.serialize();
  36838. if (this.positions) {
  36839. serializationObject.positions = this.positions;
  36840. }
  36841. if (this.normals) {
  36842. serializationObject.normals = this.normals;
  36843. }
  36844. if (this.tangents) {
  36845. serializationObject.tangents = this.tangents;
  36846. }
  36847. if (this.uvs) {
  36848. serializationObject.uvs = this.uvs;
  36849. }
  36850. if (this.uvs2) {
  36851. serializationObject.uvs2 = this.uvs2;
  36852. }
  36853. if (this.uvs3) {
  36854. serializationObject.uvs3 = this.uvs3;
  36855. }
  36856. if (this.uvs4) {
  36857. serializationObject.uvs4 = this.uvs4;
  36858. }
  36859. if (this.uvs5) {
  36860. serializationObject.uvs5 = this.uvs5;
  36861. }
  36862. if (this.uvs6) {
  36863. serializationObject.uvs6 = this.uvs6;
  36864. }
  36865. if (this.colors) {
  36866. serializationObject.colors = this.colors;
  36867. }
  36868. if (this.matricesIndices) {
  36869. serializationObject.matricesIndices = this.matricesIndices;
  36870. serializationObject.matricesIndices._isExpanded = true;
  36871. }
  36872. if (this.matricesWeights) {
  36873. serializationObject.matricesWeights = this.matricesWeights;
  36874. }
  36875. if (this.matricesIndicesExtra) {
  36876. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36877. serializationObject.matricesIndicesExtra._isExpanded = true;
  36878. }
  36879. if (this.matricesWeightsExtra) {
  36880. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36881. }
  36882. serializationObject.indices = this.indices;
  36883. return serializationObject;
  36884. };
  36885. // Statics
  36886. /**
  36887. * Extracts the vertexData from a mesh
  36888. * @param mesh the mesh from which to extract the VertexData
  36889. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36890. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36891. * @returns the object VertexData associated to the passed mesh
  36892. */
  36893. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36894. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36895. };
  36896. /**
  36897. * Extracts the vertexData from the geometry
  36898. * @param geometry the geometry from which to extract the VertexData
  36899. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36900. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36901. * @returns the object VertexData associated to the passed mesh
  36902. */
  36903. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36904. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36905. };
  36906. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36907. var result = new VertexData();
  36908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36909. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36910. }
  36911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36912. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36913. }
  36914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36915. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36916. }
  36917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36918. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36919. }
  36920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36921. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36922. }
  36923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36924. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36925. }
  36926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36927. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36928. }
  36929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36930. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36931. }
  36932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36933. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36934. }
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36936. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36937. }
  36938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36939. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36940. }
  36941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36942. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36943. }
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36945. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36946. }
  36947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36948. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36949. }
  36950. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36951. return result;
  36952. };
  36953. /**
  36954. * Creates the VertexData for a Ribbon
  36955. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36956. * * pathArray array of paths, each of which an array of successive Vector3
  36957. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36958. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36959. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36960. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36961. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36962. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36963. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36964. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36965. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36966. * @returns the VertexData of the ribbon
  36967. */
  36968. VertexData.CreateRibbon = function (options) {
  36969. var pathArray = options.pathArray;
  36970. var closeArray = options.closeArray || false;
  36971. var closePath = options.closePath || false;
  36972. var invertUV = options.invertUV || false;
  36973. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36974. var offset = options.offset || defaultOffset;
  36975. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36976. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36977. var customUV = options.uvs;
  36978. var customColors = options.colors;
  36979. var positions = [];
  36980. var indices = [];
  36981. var normals = [];
  36982. var uvs = [];
  36983. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36984. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36985. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36986. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36987. var minlg; // minimal length among all paths from pathArray
  36988. var lg = []; // array of path lengths : nb of vertex per path
  36989. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36990. var p; // path iterator
  36991. var i; // point iterator
  36992. var j; // point iterator
  36993. // if single path in pathArray
  36994. if (pathArray.length < 2) {
  36995. var ar1 = [];
  36996. var ar2 = [];
  36997. for (i = 0; i < pathArray[0].length - offset; i++) {
  36998. ar1.push(pathArray[0][i]);
  36999. ar2.push(pathArray[0][i + offset]);
  37000. }
  37001. pathArray = [ar1, ar2];
  37002. }
  37003. // positions and horizontal distances (u)
  37004. var idc = 0;
  37005. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37006. var path;
  37007. var l;
  37008. minlg = pathArray[0].length;
  37009. var vectlg;
  37010. var dist;
  37011. for (p = 0; p < pathArray.length; p++) {
  37012. uTotalDistance[p] = 0;
  37013. us[p] = [0];
  37014. path = pathArray[p];
  37015. l = path.length;
  37016. minlg = (minlg < l) ? minlg : l;
  37017. j = 0;
  37018. while (j < l) {
  37019. positions.push(path[j].x, path[j].y, path[j].z);
  37020. if (j > 0) {
  37021. vectlg = path[j].subtract(path[j - 1]).length();
  37022. dist = vectlg + uTotalDistance[p];
  37023. us[p].push(dist);
  37024. uTotalDistance[p] = dist;
  37025. }
  37026. j++;
  37027. }
  37028. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37029. j--;
  37030. positions.push(path[0].x, path[0].y, path[0].z);
  37031. vectlg = path[j].subtract(path[0]).length();
  37032. dist = vectlg + uTotalDistance[p];
  37033. us[p].push(dist);
  37034. uTotalDistance[p] = dist;
  37035. }
  37036. lg[p] = l + closePathCorr;
  37037. idx[p] = idc;
  37038. idc += (l + closePathCorr);
  37039. }
  37040. // vertical distances (v)
  37041. var path1;
  37042. var path2;
  37043. var vertex1 = null;
  37044. var vertex2 = null;
  37045. for (i = 0; i < minlg + closePathCorr; i++) {
  37046. vTotalDistance[i] = 0;
  37047. vs[i] = [0];
  37048. for (p = 0; p < pathArray.length - 1; p++) {
  37049. path1 = pathArray[p];
  37050. path2 = pathArray[p + 1];
  37051. if (i === minlg) { // closePath
  37052. vertex1 = path1[0];
  37053. vertex2 = path2[0];
  37054. }
  37055. else {
  37056. vertex1 = path1[i];
  37057. vertex2 = path2[i];
  37058. }
  37059. vectlg = vertex2.subtract(vertex1).length();
  37060. dist = vectlg + vTotalDistance[i];
  37061. vs[i].push(dist);
  37062. vTotalDistance[i] = dist;
  37063. }
  37064. if (closeArray && vertex2 && vertex1) {
  37065. path1 = pathArray[p];
  37066. path2 = pathArray[0];
  37067. if (i === minlg) { // closePath
  37068. vertex2 = path2[0];
  37069. }
  37070. vectlg = vertex2.subtract(vertex1).length();
  37071. dist = vectlg + vTotalDistance[i];
  37072. vTotalDistance[i] = dist;
  37073. }
  37074. }
  37075. // uvs
  37076. var u;
  37077. var v;
  37078. if (customUV) {
  37079. for (p = 0; p < customUV.length; p++) {
  37080. uvs.push(customUV[p].x, customUV[p].y);
  37081. }
  37082. }
  37083. else {
  37084. for (p = 0; p < pathArray.length; p++) {
  37085. for (i = 0; i < minlg + closePathCorr; i++) {
  37086. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37087. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37088. if (invertUV) {
  37089. uvs.push(v, u);
  37090. }
  37091. else {
  37092. uvs.push(u, v);
  37093. }
  37094. }
  37095. }
  37096. }
  37097. // indices
  37098. p = 0; // path index
  37099. var pi = 0; // positions array index
  37100. var l1 = lg[p] - 1; // path1 length
  37101. var l2 = lg[p + 1] - 1; // path2 length
  37102. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37103. var shft = idx[1] - idx[0]; // shift
  37104. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37105. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37106. // 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
  37107. indices.push(pi, pi + shft, pi + 1);
  37108. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37109. pi += 1;
  37110. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37111. p++;
  37112. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37113. shft = idx[0] - idx[p];
  37114. l1 = lg[p] - 1;
  37115. l2 = lg[0] - 1;
  37116. }
  37117. else {
  37118. shft = idx[p + 1] - idx[p];
  37119. l1 = lg[p] - 1;
  37120. l2 = lg[p + 1] - 1;
  37121. }
  37122. pi = idx[p];
  37123. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37124. }
  37125. }
  37126. // normals
  37127. VertexData.ComputeNormals(positions, indices, normals);
  37128. if (closePath) { // update both the first and last vertex normals to their average value
  37129. var indexFirst = 0;
  37130. var indexLast = 0;
  37131. for (p = 0; p < pathArray.length; p++) {
  37132. indexFirst = idx[p] * 3;
  37133. if (p + 1 < pathArray.length) {
  37134. indexLast = (idx[p + 1] - 1) * 3;
  37135. }
  37136. else {
  37137. indexLast = normals.length - 3;
  37138. }
  37139. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37140. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37141. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37142. normals[indexLast] = normals[indexFirst];
  37143. normals[indexLast + 1] = normals[indexFirst + 1];
  37144. normals[indexLast + 2] = normals[indexFirst + 2];
  37145. }
  37146. }
  37147. // sides
  37148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37149. // Colors
  37150. var colors = null;
  37151. if (customColors) {
  37152. colors = new Float32Array(customColors.length * 4);
  37153. for (var c = 0; c < customColors.length; c++) {
  37154. colors[c * 4] = customColors[c].r;
  37155. colors[c * 4 + 1] = customColors[c].g;
  37156. colors[c * 4 + 2] = customColors[c].b;
  37157. colors[c * 4 + 3] = customColors[c].a;
  37158. }
  37159. }
  37160. // Result
  37161. var vertexData = new VertexData();
  37162. var positions32 = new Float32Array(positions);
  37163. var normals32 = new Float32Array(normals);
  37164. var uvs32 = new Float32Array(uvs);
  37165. vertexData.indices = indices;
  37166. vertexData.positions = positions32;
  37167. vertexData.normals = normals32;
  37168. vertexData.uvs = uvs32;
  37169. if (colors) {
  37170. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37171. }
  37172. if (closePath) {
  37173. vertexData._idx = idx;
  37174. }
  37175. return vertexData;
  37176. };
  37177. /**
  37178. * Creates the VertexData for a box
  37179. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37180. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37181. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37182. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37183. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37184. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37185. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37186. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37187. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37188. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37189. * @returns the VertexData of the box
  37190. */
  37191. VertexData.CreateBox = function (options) {
  37192. var normalsSource = [
  37193. new BABYLON.Vector3(0, 0, 1),
  37194. new BABYLON.Vector3(0, 0, -1),
  37195. new BABYLON.Vector3(1, 0, 0),
  37196. new BABYLON.Vector3(-1, 0, 0),
  37197. new BABYLON.Vector3(0, 1, 0),
  37198. new BABYLON.Vector3(0, -1, 0)
  37199. ];
  37200. var indices = [];
  37201. var positions = [];
  37202. var normals = [];
  37203. var uvs = [];
  37204. var width = options.width || options.size || 1;
  37205. var height = options.height || options.size || 1;
  37206. var depth = options.depth || options.size || 1;
  37207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37208. var faceUV = options.faceUV || new Array(6);
  37209. var faceColors = options.faceColors;
  37210. var colors = [];
  37211. // default face colors and UV if undefined
  37212. for (var f = 0; f < 6; f++) {
  37213. if (faceUV[f] === undefined) {
  37214. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37215. }
  37216. if (faceColors && faceColors[f] === undefined) {
  37217. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37218. }
  37219. }
  37220. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37221. // Create each face in turn.
  37222. for (var index = 0; index < normalsSource.length; index++) {
  37223. var normal = normalsSource[index];
  37224. // Get two vectors perpendicular to the face normal and to each other.
  37225. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37226. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37227. // Six indices (two triangles) per face.
  37228. var verticesLength = positions.length / 3;
  37229. indices.push(verticesLength);
  37230. indices.push(verticesLength + 1);
  37231. indices.push(verticesLength + 2);
  37232. indices.push(verticesLength);
  37233. indices.push(verticesLength + 2);
  37234. indices.push(verticesLength + 3);
  37235. // Four vertices per face.
  37236. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37237. positions.push(vertex.x, vertex.y, vertex.z);
  37238. normals.push(normal.x, normal.y, normal.z);
  37239. uvs.push(faceUV[index].z, faceUV[index].w);
  37240. if (faceColors) {
  37241. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37242. }
  37243. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37244. positions.push(vertex.x, vertex.y, vertex.z);
  37245. normals.push(normal.x, normal.y, normal.z);
  37246. uvs.push(faceUV[index].x, faceUV[index].w);
  37247. if (faceColors) {
  37248. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37249. }
  37250. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37251. positions.push(vertex.x, vertex.y, vertex.z);
  37252. normals.push(normal.x, normal.y, normal.z);
  37253. uvs.push(faceUV[index].x, faceUV[index].y);
  37254. if (faceColors) {
  37255. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37256. }
  37257. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37258. positions.push(vertex.x, vertex.y, vertex.z);
  37259. normals.push(normal.x, normal.y, normal.z);
  37260. uvs.push(faceUV[index].z, faceUV[index].y);
  37261. if (faceColors) {
  37262. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37263. }
  37264. }
  37265. // sides
  37266. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37267. // Result
  37268. var vertexData = new VertexData();
  37269. vertexData.indices = indices;
  37270. vertexData.positions = positions;
  37271. vertexData.normals = normals;
  37272. vertexData.uvs = uvs;
  37273. if (faceColors) {
  37274. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37275. vertexData.colors = totalColors;
  37276. }
  37277. return vertexData;
  37278. };
  37279. /**
  37280. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37281. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37282. * * segments sets the number of horizontal strips optional, default 32
  37283. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37284. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37285. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37286. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37287. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37288. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37289. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37290. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37291. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37292. * @returns the VertexData of the ellipsoid
  37293. */
  37294. VertexData.CreateSphere = function (options) {
  37295. var segments = options.segments || 32;
  37296. var diameterX = options.diameterX || options.diameter || 1;
  37297. var diameterY = options.diameterY || options.diameter || 1;
  37298. var diameterZ = options.diameterZ || options.diameter || 1;
  37299. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37300. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37302. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37303. var totalZRotationSteps = 2 + segments;
  37304. var totalYRotationSteps = 2 * totalZRotationSteps;
  37305. var indices = [];
  37306. var positions = [];
  37307. var normals = [];
  37308. var uvs = [];
  37309. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37310. var normalizedZ = zRotationStep / totalZRotationSteps;
  37311. var angleZ = normalizedZ * Math.PI * slice;
  37312. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37313. var normalizedY = yRotationStep / totalYRotationSteps;
  37314. var angleY = normalizedY * Math.PI * 2 * arc;
  37315. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37316. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37317. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37318. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37319. var vertex = complete.multiply(radius);
  37320. var normal = complete.divide(radius).normalize();
  37321. positions.push(vertex.x, vertex.y, vertex.z);
  37322. normals.push(normal.x, normal.y, normal.z);
  37323. uvs.push(normalizedY, normalizedZ);
  37324. }
  37325. if (zRotationStep > 0) {
  37326. var verticesCount = positions.length / 3;
  37327. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37328. indices.push((firstIndex));
  37329. indices.push((firstIndex + 1));
  37330. indices.push(firstIndex + totalYRotationSteps + 1);
  37331. indices.push((firstIndex + totalYRotationSteps + 1));
  37332. indices.push((firstIndex + 1));
  37333. indices.push((firstIndex + totalYRotationSteps + 2));
  37334. }
  37335. }
  37336. }
  37337. // Sides
  37338. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37339. // Result
  37340. var vertexData = new VertexData();
  37341. vertexData.indices = indices;
  37342. vertexData.positions = positions;
  37343. vertexData.normals = normals;
  37344. vertexData.uvs = uvs;
  37345. return vertexData;
  37346. };
  37347. /**
  37348. * Creates the VertexData for a cylinder, cone or prism
  37349. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37350. * * height sets the height (y direction) of the cylinder, optional, default 2
  37351. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37352. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37353. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37354. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37355. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37356. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37357. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37358. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37359. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37360. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37361. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37362. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37363. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37364. * @returns the VertexData of the cylinder, cone or prism
  37365. */
  37366. VertexData.CreateCylinder = function (options) {
  37367. var height = options.height || 2;
  37368. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37369. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37370. var tessellation = options.tessellation || 24;
  37371. var subdivisions = options.subdivisions || 1;
  37372. var hasRings = options.hasRings ? true : false;
  37373. var enclose = options.enclose ? true : false;
  37374. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37375. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37376. var faceUV = options.faceUV || new Array(3);
  37377. var faceColors = options.faceColors;
  37378. // default face colors and UV if undefined
  37379. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37380. var ringNb = (hasRings) ? subdivisions : 1;
  37381. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37382. var f;
  37383. for (f = 0; f < surfaceNb; f++) {
  37384. if (faceColors && faceColors[f] === undefined) {
  37385. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37386. }
  37387. }
  37388. for (f = 0; f < surfaceNb; f++) {
  37389. if (faceUV && faceUV[f] === undefined) {
  37390. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37391. }
  37392. }
  37393. var indices = new Array();
  37394. var positions = new Array();
  37395. var normals = new Array();
  37396. var uvs = new Array();
  37397. var colors = new Array();
  37398. var angle_step = Math.PI * 2 * arc / tessellation;
  37399. var angle;
  37400. var h;
  37401. var radius;
  37402. var tan = (diameterBottom - diameterTop) / 2 / height;
  37403. var ringVertex = BABYLON.Vector3.Zero();
  37404. var ringNormal = BABYLON.Vector3.Zero();
  37405. var ringFirstVertex = BABYLON.Vector3.Zero();
  37406. var ringFirstNormal = BABYLON.Vector3.Zero();
  37407. var quadNormal = BABYLON.Vector3.Zero();
  37408. var Y = BABYLON.Axis.Y;
  37409. // positions, normals, uvs
  37410. var i;
  37411. var j;
  37412. var r;
  37413. var ringIdx = 1;
  37414. var s = 1; // surface index
  37415. var cs = 0;
  37416. var v = 0;
  37417. for (i = 0; i <= subdivisions; i++) {
  37418. h = i / subdivisions;
  37419. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37420. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37421. for (r = 0; r < ringIdx; r++) {
  37422. if (hasRings) {
  37423. s += r;
  37424. }
  37425. if (enclose) {
  37426. s += 2 * r;
  37427. }
  37428. for (j = 0; j <= tessellation; j++) {
  37429. angle = j * angle_step;
  37430. // position
  37431. ringVertex.x = Math.cos(-angle) * radius;
  37432. ringVertex.y = -height / 2 + h * height;
  37433. ringVertex.z = Math.sin(-angle) * radius;
  37434. // normal
  37435. if (diameterTop === 0 && i === subdivisions) {
  37436. // if no top cap, reuse former normals
  37437. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37438. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37439. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37440. }
  37441. else {
  37442. ringNormal.x = ringVertex.x;
  37443. ringNormal.z = ringVertex.z;
  37444. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37445. ringNormal.normalize();
  37446. }
  37447. // keep first ring vertex values for enclose
  37448. if (j === 0) {
  37449. ringFirstVertex.copyFrom(ringVertex);
  37450. ringFirstNormal.copyFrom(ringNormal);
  37451. }
  37452. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37453. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37454. if (hasRings) {
  37455. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37456. }
  37457. else {
  37458. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37459. }
  37460. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37461. if (faceColors) {
  37462. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37463. }
  37464. }
  37465. // if enclose, add four vertices and their dedicated normals
  37466. if (arc !== 1 && enclose) {
  37467. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37468. positions.push(0, ringVertex.y, 0);
  37469. positions.push(0, ringVertex.y, 0);
  37470. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37471. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37472. quadNormal.normalize();
  37473. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37474. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37475. quadNormal.normalize();
  37476. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37477. if (hasRings) {
  37478. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37479. }
  37480. else {
  37481. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37482. }
  37483. uvs.push(faceUV[s + 1].x, v);
  37484. uvs.push(faceUV[s + 1].z, v);
  37485. if (hasRings) {
  37486. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37487. }
  37488. else {
  37489. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37490. }
  37491. uvs.push(faceUV[s + 2].x, v);
  37492. uvs.push(faceUV[s + 2].z, v);
  37493. if (faceColors) {
  37494. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37495. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37496. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37497. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37498. }
  37499. }
  37500. if (cs !== s) {
  37501. cs = s;
  37502. }
  37503. }
  37504. }
  37505. // indices
  37506. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37507. var s;
  37508. i = 0;
  37509. for (s = 0; s < subdivisions; s++) {
  37510. var i0 = 0;
  37511. var i1 = 0;
  37512. var i2 = 0;
  37513. var i3 = 0;
  37514. for (j = 0; j < tessellation; j++) {
  37515. i0 = i * (e + 1) + j;
  37516. i1 = (i + 1) * (e + 1) + j;
  37517. i2 = i * (e + 1) + (j + 1);
  37518. i3 = (i + 1) * (e + 1) + (j + 1);
  37519. indices.push(i0, i1, i2);
  37520. indices.push(i3, i2, i1);
  37521. }
  37522. if (arc !== 1 && enclose) { // if enclose, add two quads
  37523. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37524. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37525. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37526. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37527. }
  37528. i = (hasRings) ? (i + 2) : (i + 1);
  37529. }
  37530. // Caps
  37531. var createCylinderCap = function (isTop) {
  37532. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37533. if (radius === 0) {
  37534. return;
  37535. }
  37536. // Cap positions, normals & uvs
  37537. var angle;
  37538. var circleVector;
  37539. var i;
  37540. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37541. var c = null;
  37542. if (faceColors) {
  37543. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37544. }
  37545. // cap center
  37546. var vbase = positions.length / 3;
  37547. var offset = isTop ? height / 2 : -height / 2;
  37548. var center = new BABYLON.Vector3(0, offset, 0);
  37549. positions.push(center.x, center.y, center.z);
  37550. normals.push(0, isTop ? 1 : -1, 0);
  37551. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37552. if (c) {
  37553. colors.push(c.r, c.g, c.b, c.a);
  37554. }
  37555. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37556. for (i = 0; i <= tessellation; i++) {
  37557. angle = Math.PI * 2 * i * arc / tessellation;
  37558. var cos = Math.cos(-angle);
  37559. var sin = Math.sin(-angle);
  37560. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37561. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37562. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37563. normals.push(0, isTop ? 1 : -1, 0);
  37564. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37565. if (c) {
  37566. colors.push(c.r, c.g, c.b, c.a);
  37567. }
  37568. }
  37569. // Cap indices
  37570. for (i = 0; i < tessellation; i++) {
  37571. if (!isTop) {
  37572. indices.push(vbase);
  37573. indices.push(vbase + (i + 1));
  37574. indices.push(vbase + (i + 2));
  37575. }
  37576. else {
  37577. indices.push(vbase);
  37578. indices.push(vbase + (i + 2));
  37579. indices.push(vbase + (i + 1));
  37580. }
  37581. }
  37582. };
  37583. // add caps to geometry
  37584. createCylinderCap(false);
  37585. createCylinderCap(true);
  37586. // Sides
  37587. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37588. var vertexData = new VertexData();
  37589. vertexData.indices = indices;
  37590. vertexData.positions = positions;
  37591. vertexData.normals = normals;
  37592. vertexData.uvs = uvs;
  37593. if (faceColors) {
  37594. vertexData.colors = colors;
  37595. }
  37596. return vertexData;
  37597. };
  37598. /**
  37599. * Creates the VertexData for a torus
  37600. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37601. * * diameter the diameter of the torus, optional default 1
  37602. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37603. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37604. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37605. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37606. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37607. * @returns the VertexData of the torus
  37608. */
  37609. VertexData.CreateTorus = function (options) {
  37610. var indices = [];
  37611. var positions = [];
  37612. var normals = [];
  37613. var uvs = [];
  37614. var diameter = options.diameter || 1;
  37615. var thickness = options.thickness || 0.5;
  37616. var tessellation = options.tessellation || 16;
  37617. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37618. var stride = tessellation + 1;
  37619. for (var i = 0; i <= tessellation; i++) {
  37620. var u = i / tessellation;
  37621. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37622. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37623. for (var j = 0; j <= tessellation; j++) {
  37624. var v = 1 - j / tessellation;
  37625. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37626. var dx = Math.cos(innerAngle);
  37627. var dy = Math.sin(innerAngle);
  37628. // Create a vertex.
  37629. var normal = new BABYLON.Vector3(dx, dy, 0);
  37630. var position = normal.scale(thickness / 2);
  37631. var textureCoordinate = new BABYLON.Vector2(u, v);
  37632. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37633. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37634. positions.push(position.x, position.y, position.z);
  37635. normals.push(normal.x, normal.y, normal.z);
  37636. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37637. // And create indices for two triangles.
  37638. var nextI = (i + 1) % stride;
  37639. var nextJ = (j + 1) % stride;
  37640. indices.push(i * stride + j);
  37641. indices.push(i * stride + nextJ);
  37642. indices.push(nextI * stride + j);
  37643. indices.push(i * stride + nextJ);
  37644. indices.push(nextI * stride + nextJ);
  37645. indices.push(nextI * stride + j);
  37646. }
  37647. }
  37648. // Sides
  37649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37650. // Result
  37651. var vertexData = new VertexData();
  37652. vertexData.indices = indices;
  37653. vertexData.positions = positions;
  37654. vertexData.normals = normals;
  37655. vertexData.uvs = uvs;
  37656. return vertexData;
  37657. };
  37658. /**
  37659. * Creates the VertexData of the LineSystem
  37660. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37661. * - lines an array of lines, each line being an array of successive Vector3
  37662. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37663. * @returns the VertexData of the LineSystem
  37664. */
  37665. VertexData.CreateLineSystem = function (options) {
  37666. var indices = [];
  37667. var positions = [];
  37668. var lines = options.lines;
  37669. var colors = options.colors;
  37670. var vertexColors = [];
  37671. var idx = 0;
  37672. for (var l = 0; l < lines.length; l++) {
  37673. var points = lines[l];
  37674. for (var index = 0; index < points.length; index++) {
  37675. positions.push(points[index].x, points[index].y, points[index].z);
  37676. if (colors) {
  37677. var color = colors[l];
  37678. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37679. }
  37680. if (index > 0) {
  37681. indices.push(idx - 1);
  37682. indices.push(idx);
  37683. }
  37684. idx++;
  37685. }
  37686. }
  37687. var vertexData = new VertexData();
  37688. vertexData.indices = indices;
  37689. vertexData.positions = positions;
  37690. if (colors) {
  37691. vertexData.colors = vertexColors;
  37692. }
  37693. return vertexData;
  37694. };
  37695. /**
  37696. * Create the VertexData for a DashedLines
  37697. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37698. * - points an array successive Vector3
  37699. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37700. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37701. * - dashNb the intended total number of dashes, optional, default 200
  37702. * @returns the VertexData for the DashedLines
  37703. */
  37704. VertexData.CreateDashedLines = function (options) {
  37705. var dashSize = options.dashSize || 3;
  37706. var gapSize = options.gapSize || 1;
  37707. var dashNb = options.dashNb || 200;
  37708. var points = options.points;
  37709. var positions = new Array();
  37710. var indices = new Array();
  37711. var curvect = BABYLON.Vector3.Zero();
  37712. var lg = 0;
  37713. var nb = 0;
  37714. var shft = 0;
  37715. var dashshft = 0;
  37716. var curshft = 0;
  37717. var idx = 0;
  37718. var i = 0;
  37719. for (i = 0; i < points.length - 1; i++) {
  37720. points[i + 1].subtractToRef(points[i], curvect);
  37721. lg += curvect.length();
  37722. }
  37723. shft = lg / dashNb;
  37724. dashshft = dashSize * shft / (dashSize + gapSize);
  37725. for (i = 0; i < points.length - 1; i++) {
  37726. points[i + 1].subtractToRef(points[i], curvect);
  37727. nb = Math.floor(curvect.length() / shft);
  37728. curvect.normalize();
  37729. for (var j = 0; j < nb; j++) {
  37730. curshft = shft * j;
  37731. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37732. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37733. indices.push(idx, idx + 1);
  37734. idx += 2;
  37735. }
  37736. }
  37737. // Result
  37738. var vertexData = new VertexData();
  37739. vertexData.positions = positions;
  37740. vertexData.indices = indices;
  37741. return vertexData;
  37742. };
  37743. /**
  37744. * Creates the VertexData for a Ground
  37745. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37746. * - width the width (x direction) of the ground, optional, default 1
  37747. * - height the height (z direction) of the ground, optional, default 1
  37748. * - subdivisions the number of subdivisions per side, optional, default 1
  37749. * @returns the VertexData of the Ground
  37750. */
  37751. VertexData.CreateGround = function (options) {
  37752. var indices = [];
  37753. var positions = [];
  37754. var normals = [];
  37755. var uvs = [];
  37756. var row, col;
  37757. var width = options.width || 1;
  37758. var height = options.height || 1;
  37759. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37760. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37761. for (row = 0; row <= subdivisionsY; row++) {
  37762. for (col = 0; col <= subdivisionsX; col++) {
  37763. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37764. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37765. positions.push(position.x, position.y, position.z);
  37766. normals.push(normal.x, normal.y, normal.z);
  37767. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37768. }
  37769. }
  37770. for (row = 0; row < subdivisionsY; row++) {
  37771. for (col = 0; col < subdivisionsX; col++) {
  37772. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37773. indices.push(col + 1 + row * (subdivisionsX + 1));
  37774. indices.push(col + row * (subdivisionsX + 1));
  37775. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37776. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37777. indices.push(col + row * (subdivisionsX + 1));
  37778. }
  37779. }
  37780. // Result
  37781. var vertexData = new VertexData();
  37782. vertexData.indices = indices;
  37783. vertexData.positions = positions;
  37784. vertexData.normals = normals;
  37785. vertexData.uvs = uvs;
  37786. return vertexData;
  37787. };
  37788. /**
  37789. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37790. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37791. * * xmin the ground minimum X coordinate, optional, default -1
  37792. * * zmin the ground minimum Z coordinate, optional, default -1
  37793. * * xmax the ground maximum X coordinate, optional, default 1
  37794. * * zmax the ground maximum Z coordinate, optional, default 1
  37795. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37796. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37797. * @returns the VertexData of the TiledGround
  37798. */
  37799. VertexData.CreateTiledGround = function (options) {
  37800. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37801. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37802. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37803. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37804. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37805. var precision = options.precision || { w: 1, h: 1 };
  37806. var indices = new Array();
  37807. var positions = new Array();
  37808. var normals = new Array();
  37809. var uvs = new Array();
  37810. var row, col, tileRow, tileCol;
  37811. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37812. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37813. precision.w = (precision.w < 1) ? 1 : precision.w;
  37814. precision.h = (precision.h < 1) ? 1 : precision.h;
  37815. var tileSize = {
  37816. 'w': (xmax - xmin) / subdivisions.w,
  37817. 'h': (zmax - zmin) / subdivisions.h
  37818. };
  37819. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37820. // Indices
  37821. var base = positions.length / 3;
  37822. var rowLength = precision.w + 1;
  37823. for (row = 0; row < precision.h; row++) {
  37824. for (col = 0; col < precision.w; col++) {
  37825. var square = [
  37826. base + col + row * rowLength,
  37827. base + (col + 1) + row * rowLength,
  37828. base + (col + 1) + (row + 1) * rowLength,
  37829. base + col + (row + 1) * rowLength
  37830. ];
  37831. indices.push(square[1]);
  37832. indices.push(square[2]);
  37833. indices.push(square[3]);
  37834. indices.push(square[0]);
  37835. indices.push(square[1]);
  37836. indices.push(square[3]);
  37837. }
  37838. }
  37839. // Position, normals and uvs
  37840. var position = BABYLON.Vector3.Zero();
  37841. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37842. for (row = 0; row <= precision.h; row++) {
  37843. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37844. for (col = 0; col <= precision.w; col++) {
  37845. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37846. position.y = 0;
  37847. positions.push(position.x, position.y, position.z);
  37848. normals.push(normal.x, normal.y, normal.z);
  37849. uvs.push(col / precision.w, row / precision.h);
  37850. }
  37851. }
  37852. }
  37853. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37854. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37855. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37856. }
  37857. }
  37858. // Result
  37859. var vertexData = new VertexData();
  37860. vertexData.indices = indices;
  37861. vertexData.positions = positions;
  37862. vertexData.normals = normals;
  37863. vertexData.uvs = uvs;
  37864. return vertexData;
  37865. };
  37866. /**
  37867. * Creates the VertexData of the Ground designed from a heightmap
  37868. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37869. * * width the width (x direction) of the ground
  37870. * * height the height (z direction) of the ground
  37871. * * subdivisions the number of subdivisions per side
  37872. * * minHeight the minimum altitude on the ground, optional, default 0
  37873. * * maxHeight the maximum altitude on the ground, optional default 1
  37874. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37875. * * buffer the array holding the image color data
  37876. * * bufferWidth the width of image
  37877. * * bufferHeight the height of image
  37878. * @returns the VertexData of the Ground designed from a heightmap
  37879. */
  37880. VertexData.CreateGroundFromHeightMap = function (options) {
  37881. var indices = [];
  37882. var positions = [];
  37883. var normals = [];
  37884. var uvs = [];
  37885. var row, col;
  37886. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37887. // Vertices
  37888. for (row = 0; row <= options.subdivisions; row++) {
  37889. for (col = 0; col <= options.subdivisions; col++) {
  37890. 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));
  37891. // Compute height
  37892. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37893. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37894. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37895. var r = options.buffer[pos] / 255.0;
  37896. var g = options.buffer[pos + 1] / 255.0;
  37897. var b = options.buffer[pos + 2] / 255.0;
  37898. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37899. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37900. // Add vertex
  37901. positions.push(position.x, position.y, position.z);
  37902. normals.push(0, 0, 0);
  37903. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37904. }
  37905. }
  37906. // Indices
  37907. for (row = 0; row < options.subdivisions; row++) {
  37908. for (col = 0; col < options.subdivisions; col++) {
  37909. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37910. indices.push(col + 1 + row * (options.subdivisions + 1));
  37911. indices.push(col + row * (options.subdivisions + 1));
  37912. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37913. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37914. indices.push(col + row * (options.subdivisions + 1));
  37915. }
  37916. }
  37917. // Normals
  37918. VertexData.ComputeNormals(positions, indices, normals);
  37919. // Result
  37920. var vertexData = new VertexData();
  37921. vertexData.indices = indices;
  37922. vertexData.positions = positions;
  37923. vertexData.normals = normals;
  37924. vertexData.uvs = uvs;
  37925. return vertexData;
  37926. };
  37927. /**
  37928. * Creates the VertexData for a Plane
  37929. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37930. * * size sets the width and height of the plane to the value of size, optional default 1
  37931. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37932. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37933. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37934. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37935. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37936. * @returns the VertexData of the box
  37937. */
  37938. VertexData.CreatePlane = function (options) {
  37939. var indices = [];
  37940. var positions = [];
  37941. var normals = [];
  37942. var uvs = [];
  37943. var width = options.width || options.size || 1;
  37944. var height = options.height || options.size || 1;
  37945. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37946. // Vertices
  37947. var halfWidth = width / 2.0;
  37948. var halfHeight = height / 2.0;
  37949. positions.push(-halfWidth, -halfHeight, 0);
  37950. normals.push(0, 0, -1.0);
  37951. uvs.push(0.0, 0.0);
  37952. positions.push(halfWidth, -halfHeight, 0);
  37953. normals.push(0, 0, -1.0);
  37954. uvs.push(1.0, 0.0);
  37955. positions.push(halfWidth, halfHeight, 0);
  37956. normals.push(0, 0, -1.0);
  37957. uvs.push(1.0, 1.0);
  37958. positions.push(-halfWidth, halfHeight, 0);
  37959. normals.push(0, 0, -1.0);
  37960. uvs.push(0.0, 1.0);
  37961. // Indices
  37962. indices.push(0);
  37963. indices.push(1);
  37964. indices.push(2);
  37965. indices.push(0);
  37966. indices.push(2);
  37967. indices.push(3);
  37968. // Sides
  37969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37970. // Result
  37971. var vertexData = new VertexData();
  37972. vertexData.indices = indices;
  37973. vertexData.positions = positions;
  37974. vertexData.normals = normals;
  37975. vertexData.uvs = uvs;
  37976. return vertexData;
  37977. };
  37978. /**
  37979. * Creates the VertexData of the Disc or regular Polygon
  37980. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37981. * * radius the radius of the disc, optional default 0.5
  37982. * * tessellation the number of polygon sides, optional, default 64
  37983. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37984. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37985. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37986. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37987. * @returns the VertexData of the box
  37988. */
  37989. VertexData.CreateDisc = function (options) {
  37990. var positions = new Array();
  37991. var indices = new Array();
  37992. var normals = new Array();
  37993. var uvs = new Array();
  37994. var radius = options.radius || 0.5;
  37995. var tessellation = options.tessellation || 64;
  37996. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37998. // positions and uvs
  37999. positions.push(0, 0, 0); // disc center first
  38000. uvs.push(0.5, 0.5);
  38001. var theta = Math.PI * 2 * arc;
  38002. var step = theta / tessellation;
  38003. for (var a = 0; a < theta; a += step) {
  38004. var x = Math.cos(a);
  38005. var y = Math.sin(a);
  38006. var u = (x + 1) / 2;
  38007. var v = (1 - y) / 2;
  38008. positions.push(radius * x, radius * y, 0);
  38009. uvs.push(u, v);
  38010. }
  38011. if (arc === 1) {
  38012. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38013. uvs.push(uvs[2], uvs[3]);
  38014. }
  38015. //indices
  38016. var vertexNb = positions.length / 3;
  38017. for (var i = 1; i < vertexNb - 1; i++) {
  38018. indices.push(i + 1, 0, i);
  38019. }
  38020. // result
  38021. VertexData.ComputeNormals(positions, indices, normals);
  38022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38023. var vertexData = new VertexData();
  38024. vertexData.indices = indices;
  38025. vertexData.positions = positions;
  38026. vertexData.normals = normals;
  38027. vertexData.uvs = uvs;
  38028. return vertexData;
  38029. };
  38030. /**
  38031. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38032. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38033. * @param polygon a mesh built from polygonTriangulation.build()
  38034. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38035. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38036. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38037. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38038. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38039. * @returns the VertexData of the Polygon
  38040. */
  38041. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38042. var faceUV = fUV || new Array(3);
  38043. var faceColors = fColors;
  38044. var colors = [];
  38045. // default face colors and UV if undefined
  38046. for (var f = 0; f < 3; f++) {
  38047. if (faceUV[f] === undefined) {
  38048. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38049. }
  38050. if (faceColors && faceColors[f] === undefined) {
  38051. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38052. }
  38053. }
  38054. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38055. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38056. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38057. var indices = polygon.getIndices();
  38058. // set face colours and textures
  38059. var idx = 0;
  38060. var face = 0;
  38061. for (var index = 0; index < normals.length; index += 3) {
  38062. //Edge Face no. 1
  38063. if (Math.abs(normals[index + 1]) < 0.001) {
  38064. face = 1;
  38065. }
  38066. //Top Face no. 0
  38067. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38068. face = 0;
  38069. }
  38070. //Bottom Face no. 2
  38071. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38072. face = 2;
  38073. }
  38074. idx = index / 3;
  38075. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38076. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38077. if (faceColors) {
  38078. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38079. }
  38080. }
  38081. // sides
  38082. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38083. // Result
  38084. var vertexData = new VertexData();
  38085. vertexData.indices = indices;
  38086. vertexData.positions = positions;
  38087. vertexData.normals = normals;
  38088. vertexData.uvs = uvs;
  38089. if (faceColors) {
  38090. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38091. vertexData.colors = totalColors;
  38092. }
  38093. return vertexData;
  38094. };
  38095. /**
  38096. * Creates the VertexData of the IcoSphere
  38097. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38098. * * radius the radius of the IcoSphere, optional default 1
  38099. * * radiusX allows stretching in the x direction, optional, default radius
  38100. * * radiusY allows stretching in the y direction, optional, default radius
  38101. * * radiusZ allows stretching in the z direction, optional, default radius
  38102. * * flat when true creates a flat shaded mesh, optional, default true
  38103. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38104. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38105. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38106. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38107. * @returns the VertexData of the IcoSphere
  38108. */
  38109. VertexData.CreateIcoSphere = function (options) {
  38110. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38111. var radius = options.radius || 1;
  38112. var flat = (options.flat === undefined) ? true : options.flat;
  38113. var subdivisions = options.subdivisions || 4;
  38114. var radiusX = options.radiusX || radius;
  38115. var radiusY = options.radiusY || radius;
  38116. var radiusZ = options.radiusZ || radius;
  38117. var t = (1 + Math.sqrt(5)) / 2;
  38118. // 12 vertex x,y,z
  38119. var ico_vertices = [
  38120. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38121. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38122. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38123. ];
  38124. // index of 3 vertex makes a face of icopshere
  38125. var ico_indices = [
  38126. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38127. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38128. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38129. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38130. ];
  38131. // vertex for uv have aliased position, not for UV
  38132. var vertices_unalias_id = [
  38133. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38134. // vertex alias
  38135. 0,
  38136. 2,
  38137. 3,
  38138. 3,
  38139. 3,
  38140. 4,
  38141. 7,
  38142. 8,
  38143. 9,
  38144. 9,
  38145. 10,
  38146. 11 // 23: B + 12
  38147. ];
  38148. // uv as integer step (not pixels !)
  38149. var ico_vertexuv = [
  38150. 5, 1, 3, 1, 6, 4, 0, 0,
  38151. 5, 3, 4, 2, 2, 2, 4, 0,
  38152. 2, 0, 1, 1, 6, 0, 6, 2,
  38153. // vertex alias (for same vertex on different faces)
  38154. 0, 4,
  38155. 3, 3,
  38156. 4, 4,
  38157. 3, 1,
  38158. 4, 2,
  38159. 4, 4,
  38160. 0, 2,
  38161. 1, 1,
  38162. 2, 2,
  38163. 3, 3,
  38164. 1, 3,
  38165. 2, 4 // 23: B + 12
  38166. ];
  38167. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38168. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38169. // First island of uv mapping
  38170. // v = 4h 3+ 2
  38171. // v = 3h 9+ 4
  38172. // v = 2h 9+ 5 B
  38173. // v = 1h 9 1 0
  38174. // v = 0h 3 8 7 A
  38175. // u = 0 1 2 3 4 5 6 *a
  38176. // Second island of uv mapping
  38177. // v = 4h 0+ B+ 4+
  38178. // v = 3h A+ 2+
  38179. // v = 2h 7+ 6 3+
  38180. // v = 1h 8+ 3+
  38181. // v = 0h
  38182. // u = 0 1 2 3 4 5 6 *a
  38183. // Face layout on texture UV mapping
  38184. // ============
  38185. // \ 4 /\ 16 / ======
  38186. // \ / \ / /\ 11 /
  38187. // \/ 7 \/ / \ /
  38188. // ======= / 10 \/
  38189. // /\ 17 /\ =======
  38190. // / \ / \ \ 15 /\
  38191. // / 8 \/ 12 \ \ / \
  38192. // ============ \/ 6 \
  38193. // \ 18 /\ ============
  38194. // \ / \ \ 5 /\ 0 /
  38195. // \/ 13 \ \ / \ /
  38196. // ======= \/ 1 \/
  38197. // =============
  38198. // /\ 19 /\ 2 /\
  38199. // / \ / \ / \
  38200. // / 14 \/ 9 \/ 3 \
  38201. // ===================
  38202. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38203. var ustep = 138 / 1024;
  38204. var vstep = 239 / 1024;
  38205. var uoffset = 60 / 1024;
  38206. var voffset = 26 / 1024;
  38207. // Second island should have margin, not to touch the first island
  38208. // avoid any borderline artefact in pixel rounding
  38209. var island_u_offset = -40 / 1024;
  38210. var island_v_offset = +20 / 1024;
  38211. // face is either island 0 or 1 :
  38212. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38213. var island = [
  38214. 0, 0, 0, 0, 1,
  38215. 0, 0, 1, 1, 0,
  38216. 0, 0, 1, 1, 0,
  38217. 0, 1, 1, 1, 0 // 15 - 19
  38218. ];
  38219. var indices = new Array();
  38220. var positions = new Array();
  38221. var normals = new Array();
  38222. var uvs = new Array();
  38223. var current_indice = 0;
  38224. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38225. var face_vertex_pos = new Array(3);
  38226. var face_vertex_uv = new Array(3);
  38227. var v012;
  38228. for (v012 = 0; v012 < 3; v012++) {
  38229. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38230. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38231. }
  38232. // create all with normals
  38233. for (var face = 0; face < 20; face++) {
  38234. // 3 vertex per face
  38235. for (v012 = 0; v012 < 3; v012++) {
  38236. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38237. var v_id = ico_indices[3 * face + v012];
  38238. // vertex have 3D position (x,y,z)
  38239. 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]);
  38240. // Normalize to get normal, then scale to radius
  38241. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38242. // uv Coordinates from vertex ID
  38243. 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);
  38244. }
  38245. // Subdivide the face (interpolate pos, norm, uv)
  38246. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38247. // - norm is linear interpolation of vertex corner normal
  38248. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38249. // - uv is linear interpolation
  38250. //
  38251. // Topology is as below for sub-divide by 2
  38252. // vertex shown as v0,v1,v2
  38253. // interp index is i1 to progress in range [v0,v1[
  38254. // interp index is i2 to progress in range [v0,v2[
  38255. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38256. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38257. //
  38258. //
  38259. // i2 v2
  38260. // ^ ^
  38261. // / / \
  38262. // / / \
  38263. // / / \
  38264. // / / (0,1) \
  38265. // / #---------\
  38266. // / / \ (0,0)'/ \
  38267. // / / \ / \
  38268. // / / \ / \
  38269. // / / (0,0) \ / (1,0) \
  38270. // / #---------#---------\
  38271. // v0 v1
  38272. //
  38273. // --------------------> i1
  38274. //
  38275. // interp of (i1,i2):
  38276. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38277. // along i1 : lerp(x0,x1, i1/(S-i2))
  38278. //
  38279. // centroid of triangle is needed to get help normal computation
  38280. // (c1,c2) are used for centroid location
  38281. var interp_vertex = function (i1, i2, c1, c2) {
  38282. // vertex is interpolated from
  38283. // - face_vertex_pos[0..2]
  38284. // - face_vertex_uv[0..2]
  38285. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38286. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38287. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38288. pos_interp.normalize();
  38289. var vertex_normal;
  38290. if (flat) {
  38291. // in flat mode, recalculate normal as face centroid normal
  38292. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38293. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38294. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38295. }
  38296. else {
  38297. // in smooth mode, recalculate normal from each single vertex position
  38298. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38299. }
  38300. // Vertex normal need correction due to X,Y,Z radius scaling
  38301. vertex_normal.x /= radiusX;
  38302. vertex_normal.y /= radiusY;
  38303. vertex_normal.z /= radiusZ;
  38304. vertex_normal.normalize();
  38305. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38306. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38307. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38308. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38309. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38310. uvs.push(uv_interp.x, uv_interp.y);
  38311. // push each vertex has member of a face
  38312. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38313. indices.push(current_indice);
  38314. current_indice++;
  38315. };
  38316. for (var i2 = 0; i2 < subdivisions; i2++) {
  38317. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38318. // face : (i1,i2) for /\ :
  38319. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38320. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38321. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38322. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38323. if (i1 + i2 + 1 < subdivisions) {
  38324. // face : (i1,i2)' for \/ :
  38325. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38326. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38327. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38328. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38329. }
  38330. }
  38331. }
  38332. }
  38333. // Sides
  38334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38335. // Result
  38336. var vertexData = new VertexData();
  38337. vertexData.indices = indices;
  38338. vertexData.positions = positions;
  38339. vertexData.normals = normals;
  38340. vertexData.uvs = uvs;
  38341. return vertexData;
  38342. };
  38343. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38344. /**
  38345. * Creates the VertexData for a Polyhedron
  38346. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38347. * * type provided types are:
  38348. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38349. * * 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)
  38350. * * size the size of the IcoSphere, optional default 1
  38351. * * sizeX allows stretching in the x direction, optional, default size
  38352. * * sizeY allows stretching in the y direction, optional, default size
  38353. * * sizeZ allows stretching in the z direction, optional, default size
  38354. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38355. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38356. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38357. * * flat when true creates a flat shaded mesh, optional, default true
  38358. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38359. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38360. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38361. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38362. * @returns the VertexData of the Polyhedron
  38363. */
  38364. VertexData.CreatePolyhedron = function (options) {
  38365. // provided polyhedron types :
  38366. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38367. // 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)
  38368. var polyhedra = [];
  38369. 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]] };
  38370. 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]] };
  38371. polyhedra[2] = {
  38372. 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]],
  38373. 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]]
  38374. };
  38375. polyhedra[3] = {
  38376. 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]],
  38377. 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]]
  38378. };
  38379. polyhedra[4] = {
  38380. 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]],
  38381. 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]]
  38382. };
  38383. 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]] };
  38384. 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]] };
  38385. 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]] };
  38386. 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]] };
  38387. 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]] };
  38388. 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]] };
  38389. 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]] };
  38390. 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]] };
  38391. 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]] };
  38392. polyhedra[14] = {
  38393. 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]],
  38394. 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]]
  38395. };
  38396. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38397. var size = options.size;
  38398. var sizeX = options.sizeX || size || 1;
  38399. var sizeY = options.sizeY || size || 1;
  38400. var sizeZ = options.sizeZ || size || 1;
  38401. var data = options.custom || polyhedra[type];
  38402. var nbfaces = data.face.length;
  38403. var faceUV = options.faceUV || new Array(nbfaces);
  38404. var faceColors = options.faceColors;
  38405. var flat = (options.flat === undefined) ? true : options.flat;
  38406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38407. var positions = new Array();
  38408. var indices = new Array();
  38409. var normals = new Array();
  38410. var uvs = new Array();
  38411. var colors = new Array();
  38412. var index = 0;
  38413. var faceIdx = 0; // face cursor in the array "indexes"
  38414. var indexes = new Array();
  38415. var i = 0;
  38416. var f = 0;
  38417. var u, v, ang, x, y, tmp;
  38418. // default face colors and UV if undefined
  38419. if (flat) {
  38420. for (f = 0; f < nbfaces; f++) {
  38421. if (faceColors && faceColors[f] === undefined) {
  38422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38423. }
  38424. if (faceUV && faceUV[f] === undefined) {
  38425. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38426. }
  38427. }
  38428. }
  38429. if (!flat) {
  38430. for (i = 0; i < data.vertex.length; i++) {
  38431. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38432. uvs.push(0, 0);
  38433. }
  38434. for (f = 0; f < nbfaces; f++) {
  38435. for (i = 0; i < data.face[f].length - 2; i++) {
  38436. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38437. }
  38438. }
  38439. }
  38440. else {
  38441. for (f = 0; f < nbfaces; f++) {
  38442. var fl = data.face[f].length; // number of vertices of the current face
  38443. ang = 2 * Math.PI / fl;
  38444. x = 0.5 * Math.tan(ang / 2);
  38445. y = 0.5;
  38446. // positions, uvs, colors
  38447. for (i = 0; i < fl; i++) {
  38448. // positions
  38449. 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);
  38450. indexes.push(index);
  38451. index++;
  38452. // uvs
  38453. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38454. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38455. uvs.push(u, v);
  38456. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38457. y = x * Math.sin(ang) + y * Math.cos(ang);
  38458. x = tmp;
  38459. // colors
  38460. if (faceColors) {
  38461. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38462. }
  38463. }
  38464. // indices from indexes
  38465. for (i = 0; i < fl - 2; i++) {
  38466. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38467. }
  38468. faceIdx += fl;
  38469. }
  38470. }
  38471. VertexData.ComputeNormals(positions, indices, normals);
  38472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38473. var vertexData = new VertexData();
  38474. vertexData.positions = positions;
  38475. vertexData.indices = indices;
  38476. vertexData.normals = normals;
  38477. vertexData.uvs = uvs;
  38478. if (faceColors && flat) {
  38479. vertexData.colors = colors;
  38480. }
  38481. return vertexData;
  38482. };
  38483. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38484. /**
  38485. * Creates the VertexData for a TorusKnot
  38486. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38487. * * radius the radius of the torus knot, optional, default 2
  38488. * * tube the thickness of the tube, optional, default 0.5
  38489. * * radialSegments the number of sides on each tube segments, optional, default 32
  38490. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38491. * * p the number of windings around the z axis, optional, default 2
  38492. * * q the number of windings around the x axis, optional, default 3
  38493. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38494. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38495. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38496. * @returns the VertexData of the Torus Knot
  38497. */
  38498. VertexData.CreateTorusKnot = function (options) {
  38499. var indices = new Array();
  38500. var positions = new Array();
  38501. var normals = new Array();
  38502. var uvs = new Array();
  38503. var radius = options.radius || 2;
  38504. var tube = options.tube || 0.5;
  38505. var radialSegments = options.radialSegments || 32;
  38506. var tubularSegments = options.tubularSegments || 32;
  38507. var p = options.p || 2;
  38508. var q = options.q || 3;
  38509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38510. // Helper
  38511. var getPos = function (angle) {
  38512. var cu = Math.cos(angle);
  38513. var su = Math.sin(angle);
  38514. var quOverP = q / p * angle;
  38515. var cs = Math.cos(quOverP);
  38516. var tx = radius * (2 + cs) * 0.5 * cu;
  38517. var ty = radius * (2 + cs) * su * 0.5;
  38518. var tz = radius * Math.sin(quOverP) * 0.5;
  38519. return new BABYLON.Vector3(tx, ty, tz);
  38520. };
  38521. // Vertices
  38522. var i;
  38523. var j;
  38524. for (i = 0; i <= radialSegments; i++) {
  38525. var modI = i % radialSegments;
  38526. var u = modI / radialSegments * 2 * p * Math.PI;
  38527. var p1 = getPos(u);
  38528. var p2 = getPos(u + 0.01);
  38529. var tang = p2.subtract(p1);
  38530. var n = p2.add(p1);
  38531. var bitan = BABYLON.Vector3.Cross(tang, n);
  38532. n = BABYLON.Vector3.Cross(bitan, tang);
  38533. bitan.normalize();
  38534. n.normalize();
  38535. for (j = 0; j < tubularSegments; j++) {
  38536. var modJ = j % tubularSegments;
  38537. var v = modJ / tubularSegments * 2 * Math.PI;
  38538. var cx = -tube * Math.cos(v);
  38539. var cy = tube * Math.sin(v);
  38540. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38541. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38542. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38543. uvs.push(i / radialSegments);
  38544. uvs.push(j / tubularSegments);
  38545. }
  38546. }
  38547. for (i = 0; i < radialSegments; i++) {
  38548. for (j = 0; j < tubularSegments; j++) {
  38549. var jNext = (j + 1) % tubularSegments;
  38550. var a = i * tubularSegments + j;
  38551. var b = (i + 1) * tubularSegments + j;
  38552. var c = (i + 1) * tubularSegments + jNext;
  38553. var d = i * tubularSegments + jNext;
  38554. indices.push(d);
  38555. indices.push(b);
  38556. indices.push(a);
  38557. indices.push(d);
  38558. indices.push(c);
  38559. indices.push(b);
  38560. }
  38561. }
  38562. // Normals
  38563. VertexData.ComputeNormals(positions, indices, normals);
  38564. // Sides
  38565. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38566. // Result
  38567. var vertexData = new VertexData();
  38568. vertexData.indices = indices;
  38569. vertexData.positions = positions;
  38570. vertexData.normals = normals;
  38571. vertexData.uvs = uvs;
  38572. return vertexData;
  38573. };
  38574. // Tools
  38575. /**
  38576. * Compute normals for given positions and indices
  38577. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38578. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38579. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38580. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38581. * * facetNormals : optional array of facet normals (vector3)
  38582. * * facetPositions : optional array of facet positions (vector3)
  38583. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38584. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38585. * * bInfo : optional bounding info, required for facetPartitioning computation
  38586. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38587. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38588. * * useRightHandedSystem: optional boolean to for right handed system computation
  38589. * * depthSort : optional boolean to enable the facet depth sort computation
  38590. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38591. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38592. */
  38593. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38594. // temporary scalar variables
  38595. var index = 0; // facet index
  38596. var p1p2x = 0.0; // p1p2 vector x coordinate
  38597. var p1p2y = 0.0; // p1p2 vector y coordinate
  38598. var p1p2z = 0.0; // p1p2 vector z coordinate
  38599. var p3p2x = 0.0; // p3p2 vector x coordinate
  38600. var p3p2y = 0.0; // p3p2 vector y coordinate
  38601. var p3p2z = 0.0; // p3p2 vector z coordinate
  38602. var faceNormalx = 0.0; // facet normal x coordinate
  38603. var faceNormaly = 0.0; // facet normal y coordinate
  38604. var faceNormalz = 0.0; // facet normal z coordinate
  38605. var length = 0.0; // facet normal length before normalization
  38606. var v1x = 0; // vector1 x index in the positions array
  38607. var v1y = 0; // vector1 y index in the positions array
  38608. var v1z = 0; // vector1 z index in the positions array
  38609. var v2x = 0; // vector2 x index in the positions array
  38610. var v2y = 0; // vector2 y index in the positions array
  38611. var v2z = 0; // vector2 z index in the positions array
  38612. var v3x = 0; // vector3 x index in the positions array
  38613. var v3y = 0; // vector3 y index in the positions array
  38614. var v3z = 0; // vector3 z index in the positions array
  38615. var computeFacetNormals = false;
  38616. var computeFacetPositions = false;
  38617. var computeFacetPartitioning = false;
  38618. var computeDepthSort = false;
  38619. var faceNormalSign = 1;
  38620. var ratio = 0;
  38621. var distanceTo = null;
  38622. if (options) {
  38623. computeFacetNormals = (options.facetNormals) ? true : false;
  38624. computeFacetPositions = (options.facetPositions) ? true : false;
  38625. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38626. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38627. ratio = options.ratio || 0;
  38628. computeDepthSort = (options.depthSort) ? true : false;
  38629. distanceTo = (options.distanceTo);
  38630. if (computeDepthSort) {
  38631. if (distanceTo === undefined) {
  38632. distanceTo = BABYLON.Vector3.Zero();
  38633. }
  38634. var depthSortedFacets = options.depthSortedFacets;
  38635. }
  38636. }
  38637. // facetPartitioning reinit if needed
  38638. var xSubRatio = 0;
  38639. var ySubRatio = 0;
  38640. var zSubRatio = 0;
  38641. var subSq = 0;
  38642. if (computeFacetPartitioning && options && options.bbSize) {
  38643. var ox = 0; // X partitioning index for facet position
  38644. var oy = 0; // Y partinioning index for facet position
  38645. var oz = 0; // Z partinioning index for facet position
  38646. var b1x = 0; // X partitioning index for facet v1 vertex
  38647. var b1y = 0; // Y partitioning index for facet v1 vertex
  38648. var b1z = 0; // z partitioning index for facet v1 vertex
  38649. var b2x = 0; // X partitioning index for facet v2 vertex
  38650. var b2y = 0; // Y partitioning index for facet v2 vertex
  38651. var b2z = 0; // Z partitioning index for facet v2 vertex
  38652. var b3x = 0; // X partitioning index for facet v3 vertex
  38653. var b3y = 0; // Y partitioning index for facet v3 vertex
  38654. var b3z = 0; // Z partitioning index for facet v3 vertex
  38655. var block_idx_o = 0; // facet barycenter block index
  38656. var block_idx_v1 = 0; // v1 vertex block index
  38657. var block_idx_v2 = 0; // v2 vertex block index
  38658. var block_idx_v3 = 0; // v3 vertex block index
  38659. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38660. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38661. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38662. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38663. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38664. subSq = options.subDiv.max * options.subDiv.max;
  38665. options.facetPartitioning.length = 0;
  38666. }
  38667. // reset the normals
  38668. for (index = 0; index < positions.length; index++) {
  38669. normals[index] = 0.0;
  38670. }
  38671. // Loop : 1 indice triplet = 1 facet
  38672. var nbFaces = (indices.length / 3) | 0;
  38673. for (index = 0; index < nbFaces; index++) {
  38674. // get the indexes of the coordinates of each vertex of the facet
  38675. v1x = indices[index * 3] * 3;
  38676. v1y = v1x + 1;
  38677. v1z = v1x + 2;
  38678. v2x = indices[index * 3 + 1] * 3;
  38679. v2y = v2x + 1;
  38680. v2z = v2x + 2;
  38681. v3x = indices[index * 3 + 2] * 3;
  38682. v3y = v3x + 1;
  38683. v3z = v3x + 2;
  38684. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38685. p1p2y = positions[v1y] - positions[v2y];
  38686. p1p2z = positions[v1z] - positions[v2z];
  38687. p3p2x = positions[v3x] - positions[v2x];
  38688. p3p2y = positions[v3y] - positions[v2y];
  38689. p3p2z = positions[v3z] - positions[v2z];
  38690. // compute the face normal with the cross product
  38691. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38692. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38693. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38694. // normalize this normal and store it in the array facetData
  38695. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38696. length = (length === 0) ? 1.0 : length;
  38697. faceNormalx /= length;
  38698. faceNormaly /= length;
  38699. faceNormalz /= length;
  38700. if (computeFacetNormals && options) {
  38701. options.facetNormals[index].x = faceNormalx;
  38702. options.facetNormals[index].y = faceNormaly;
  38703. options.facetNormals[index].z = faceNormalz;
  38704. }
  38705. if (computeFacetPositions && options) {
  38706. // compute and the facet barycenter coordinates in the array facetPositions
  38707. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38708. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38709. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38710. }
  38711. if (computeFacetPartitioning && options) {
  38712. // store the facet indexes in arrays in the main facetPartitioning array :
  38713. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38714. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38715. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38716. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38717. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38718. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38719. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38720. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38721. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38722. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38723. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38724. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38725. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38726. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38727. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38728. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38729. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38730. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38731. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38732. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38733. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38734. // push each facet index in each block containing the vertex
  38735. options.facetPartitioning[block_idx_v1].push(index);
  38736. if (block_idx_v2 != block_idx_v1) {
  38737. options.facetPartitioning[block_idx_v2].push(index);
  38738. }
  38739. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38740. options.facetPartitioning[block_idx_v3].push(index);
  38741. }
  38742. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38743. options.facetPartitioning[block_idx_o].push(index);
  38744. }
  38745. }
  38746. if (computeDepthSort && options && options.facetPositions) {
  38747. var dsf = depthSortedFacets[index];
  38748. dsf.ind = index * 3;
  38749. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38750. }
  38751. // compute the normals anyway
  38752. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38753. normals[v1y] += faceNormaly;
  38754. normals[v1z] += faceNormalz;
  38755. normals[v2x] += faceNormalx;
  38756. normals[v2y] += faceNormaly;
  38757. normals[v2z] += faceNormalz;
  38758. normals[v3x] += faceNormalx;
  38759. normals[v3y] += faceNormaly;
  38760. normals[v3z] += faceNormalz;
  38761. }
  38762. // last normalization of each normal
  38763. for (index = 0; index < normals.length / 3; index++) {
  38764. faceNormalx = normals[index * 3];
  38765. faceNormaly = normals[index * 3 + 1];
  38766. faceNormalz = normals[index * 3 + 2];
  38767. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38768. length = (length === 0) ? 1.0 : length;
  38769. faceNormalx /= length;
  38770. faceNormaly /= length;
  38771. faceNormalz /= length;
  38772. normals[index * 3] = faceNormalx;
  38773. normals[index * 3 + 1] = faceNormaly;
  38774. normals[index * 3 + 2] = faceNormalz;
  38775. }
  38776. };
  38777. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38778. var li = indices.length;
  38779. var ln = normals.length;
  38780. var i;
  38781. var n;
  38782. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38783. switch (sideOrientation) {
  38784. case BABYLON.Mesh.FRONTSIDE:
  38785. // nothing changed
  38786. break;
  38787. case BABYLON.Mesh.BACKSIDE:
  38788. var tmp;
  38789. // indices
  38790. for (i = 0; i < li; i += 3) {
  38791. tmp = indices[i];
  38792. indices[i] = indices[i + 2];
  38793. indices[i + 2] = tmp;
  38794. }
  38795. // normals
  38796. for (n = 0; n < ln; n++) {
  38797. normals[n] = -normals[n];
  38798. }
  38799. break;
  38800. case BABYLON.Mesh.DOUBLESIDE:
  38801. // positions
  38802. var lp = positions.length;
  38803. var l = lp / 3;
  38804. for (var p = 0; p < lp; p++) {
  38805. positions[lp + p] = positions[p];
  38806. }
  38807. // indices
  38808. for (i = 0; i < li; i += 3) {
  38809. indices[i + li] = indices[i + 2] + l;
  38810. indices[i + 1 + li] = indices[i + 1] + l;
  38811. indices[i + 2 + li] = indices[i] + l;
  38812. }
  38813. // normals
  38814. for (n = 0; n < ln; n++) {
  38815. normals[ln + n] = -normals[n];
  38816. }
  38817. // uvs
  38818. var lu = uvs.length;
  38819. var u = 0;
  38820. for (u = 0; u < lu; u++) {
  38821. uvs[u + lu] = uvs[u];
  38822. }
  38823. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38824. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38825. u = 0;
  38826. for (i = 0; i < lu / 2; i++) {
  38827. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38828. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38829. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38830. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38831. u += 2;
  38832. }
  38833. break;
  38834. }
  38835. };
  38836. /**
  38837. * Applies VertexData created from the imported parameters to the geometry
  38838. * @param parsedVertexData the parsed data from an imported file
  38839. * @param geometry the geometry to apply the VertexData to
  38840. */
  38841. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38842. var vertexData = new VertexData();
  38843. // positions
  38844. var positions = parsedVertexData.positions;
  38845. if (positions) {
  38846. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38847. }
  38848. // normals
  38849. var normals = parsedVertexData.normals;
  38850. if (normals) {
  38851. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38852. }
  38853. // tangents
  38854. var tangents = parsedVertexData.tangents;
  38855. if (tangents) {
  38856. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38857. }
  38858. // uvs
  38859. var uvs = parsedVertexData.uvs;
  38860. if (uvs) {
  38861. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38862. }
  38863. // uv2s
  38864. var uv2s = parsedVertexData.uv2s;
  38865. if (uv2s) {
  38866. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38867. }
  38868. // uv3s
  38869. var uv3s = parsedVertexData.uv3s;
  38870. if (uv3s) {
  38871. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38872. }
  38873. // uv4s
  38874. var uv4s = parsedVertexData.uv4s;
  38875. if (uv4s) {
  38876. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38877. }
  38878. // uv5s
  38879. var uv5s = parsedVertexData.uv5s;
  38880. if (uv5s) {
  38881. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38882. }
  38883. // uv6s
  38884. var uv6s = parsedVertexData.uv6s;
  38885. if (uv6s) {
  38886. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38887. }
  38888. // colors
  38889. var colors = parsedVertexData.colors;
  38890. if (colors) {
  38891. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38892. }
  38893. // matricesIndices
  38894. var matricesIndices = parsedVertexData.matricesIndices;
  38895. if (matricesIndices) {
  38896. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38897. }
  38898. // matricesWeights
  38899. var matricesWeights = parsedVertexData.matricesWeights;
  38900. if (matricesWeights) {
  38901. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38902. }
  38903. // indices
  38904. var indices = parsedVertexData.indices;
  38905. if (indices) {
  38906. vertexData.indices = indices;
  38907. }
  38908. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38909. };
  38910. return VertexData;
  38911. }());
  38912. BABYLON.VertexData = VertexData;
  38913. })(BABYLON || (BABYLON = {}));
  38914. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38915. var BABYLON;
  38916. (function (BABYLON) {
  38917. /**
  38918. * Class used to store geometry data (vertex buffers + index buffer)
  38919. */
  38920. var Geometry = /** @class */ (function () {
  38921. /**
  38922. * Creates a new geometry
  38923. * @param id defines the unique ID
  38924. * @param scene defines the hosting scene
  38925. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38926. * @param updatable defines if geometry must be updatable (false by default)
  38927. * @param mesh defines the mesh that will be associated with the geometry
  38928. */
  38929. function Geometry(id, scene, vertexData, updatable, mesh) {
  38930. if (updatable === void 0) { updatable = false; }
  38931. if (mesh === void 0) { mesh = null; }
  38932. /**
  38933. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38934. */
  38935. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38936. this._totalVertices = 0;
  38937. this._isDisposed = false;
  38938. this._indexBufferIsUpdatable = false;
  38939. this.id = id;
  38940. this._engine = scene.getEngine();
  38941. this._meshes = [];
  38942. this._scene = scene;
  38943. //Init vertex buffer cache
  38944. this._vertexBuffers = {};
  38945. this._indices = [];
  38946. this._updatable = updatable;
  38947. // vertexData
  38948. if (vertexData) {
  38949. this.setAllVerticesData(vertexData, updatable);
  38950. }
  38951. else {
  38952. this._totalVertices = 0;
  38953. this._indices = [];
  38954. }
  38955. if (this._engine.getCaps().vertexArrayObject) {
  38956. this._vertexArrayObjects = {};
  38957. }
  38958. // applyToMesh
  38959. if (mesh) {
  38960. if (mesh.getClassName() === "LinesMesh") {
  38961. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38962. this._updateExtend();
  38963. }
  38964. this.applyToMesh(mesh);
  38965. mesh.computeWorldMatrix(true);
  38966. }
  38967. }
  38968. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38969. /**
  38970. * 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
  38971. */
  38972. get: function () {
  38973. return this._boundingBias;
  38974. },
  38975. /**
  38976. * 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
  38977. */
  38978. set: function (value) {
  38979. if (this._boundingBias && this._boundingBias.equals(value)) {
  38980. return;
  38981. }
  38982. this._boundingBias = value.clone();
  38983. this._updateBoundingInfo(true, null);
  38984. },
  38985. enumerable: true,
  38986. configurable: true
  38987. });
  38988. /**
  38989. * Static function used to attach a new empty geometry to a mesh
  38990. * @param mesh defines the mesh to attach the geometry to
  38991. * @returns the new {BABYLON.Geometry}
  38992. */
  38993. Geometry.CreateGeometryForMesh = function (mesh) {
  38994. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38995. geometry.applyToMesh(mesh);
  38996. return geometry;
  38997. };
  38998. Object.defineProperty(Geometry.prototype, "extend", {
  38999. /**
  39000. * Gets the current extend of the geometry
  39001. */
  39002. get: function () {
  39003. return this._extend;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. /**
  39009. * Gets the hosting scene
  39010. * @returns the hosting {BABYLON.Scene}
  39011. */
  39012. Geometry.prototype.getScene = function () {
  39013. return this._scene;
  39014. };
  39015. /**
  39016. * Gets the hosting engine
  39017. * @returns the hosting {BABYLON.Engine}
  39018. */
  39019. Geometry.prototype.getEngine = function () {
  39020. return this._engine;
  39021. };
  39022. /**
  39023. * Defines if the geometry is ready to use
  39024. * @returns true if the geometry is ready to be used
  39025. */
  39026. Geometry.prototype.isReady = function () {
  39027. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39028. };
  39029. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39030. /**
  39031. * Gets a value indicating that the geometry should not be serialized
  39032. */
  39033. get: function () {
  39034. for (var index = 0; index < this._meshes.length; index++) {
  39035. if (!this._meshes[index].doNotSerialize) {
  39036. return false;
  39037. }
  39038. }
  39039. return true;
  39040. },
  39041. enumerable: true,
  39042. configurable: true
  39043. });
  39044. /** @hidden */
  39045. Geometry.prototype._rebuild = function () {
  39046. if (this._vertexArrayObjects) {
  39047. this._vertexArrayObjects = {};
  39048. }
  39049. // Index buffer
  39050. if (this._meshes.length !== 0 && this._indices) {
  39051. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39052. }
  39053. // Vertex buffers
  39054. for (var key in this._vertexBuffers) {
  39055. var vertexBuffer = this._vertexBuffers[key];
  39056. vertexBuffer._rebuild();
  39057. }
  39058. };
  39059. /**
  39060. * Affects all gemetry data in one call
  39061. * @param vertexData defines the geometry data
  39062. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39063. */
  39064. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39065. vertexData.applyToGeometry(this, updatable);
  39066. this.notifyUpdate();
  39067. };
  39068. /**
  39069. * Set specific vertex data
  39070. * @param kind defines the data kind (Position, normal, etc...)
  39071. * @param data defines the vertex data to use
  39072. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39073. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39074. */
  39075. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39076. if (updatable === void 0) { updatable = false; }
  39077. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39078. this.setVerticesBuffer(buffer);
  39079. };
  39080. /**
  39081. * Removes a specific vertex data
  39082. * @param kind defines the data kind (Position, normal, etc...)
  39083. */
  39084. Geometry.prototype.removeVerticesData = function (kind) {
  39085. if (this._vertexBuffers[kind]) {
  39086. this._vertexBuffers[kind].dispose();
  39087. delete this._vertexBuffers[kind];
  39088. }
  39089. };
  39090. /**
  39091. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39092. * @param buffer defines the vertex buffer to use
  39093. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39094. */
  39095. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39096. if (totalVertices === void 0) { totalVertices = null; }
  39097. var kind = buffer.getKind();
  39098. if (this._vertexBuffers[kind]) {
  39099. this._vertexBuffers[kind].dispose();
  39100. }
  39101. this._vertexBuffers[kind] = buffer;
  39102. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39103. var data = buffer.getData();
  39104. if (totalVertices != null) {
  39105. this._totalVertices = totalVertices;
  39106. }
  39107. else {
  39108. if (data != null) {
  39109. this._totalVertices = data.length / (buffer.byteStride / 4);
  39110. }
  39111. }
  39112. this._updateExtend(data);
  39113. this._resetPointsArrayCache();
  39114. var meshes = this._meshes;
  39115. var numOfMeshes = meshes.length;
  39116. for (var index = 0; index < numOfMeshes; index++) {
  39117. var mesh = meshes[index];
  39118. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39119. mesh._createGlobalSubMesh(false);
  39120. mesh.computeWorldMatrix(true);
  39121. }
  39122. }
  39123. this.notifyUpdate(kind);
  39124. if (this._vertexArrayObjects) {
  39125. this._disposeVertexArrayObjects();
  39126. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39127. }
  39128. };
  39129. /**
  39130. * Update a specific vertex buffer
  39131. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39132. * It will do nothing if the buffer is not updatable
  39133. * @param kind defines the data kind (Position, normal, etc...)
  39134. * @param data defines the data to use
  39135. * @param offset defines the offset in the target buffer where to store the data
  39136. * @param useBytes set to true if the offset is in bytes
  39137. */
  39138. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39139. if (useBytes === void 0) { useBytes = false; }
  39140. var vertexBuffer = this.getVertexBuffer(kind);
  39141. if (!vertexBuffer) {
  39142. return;
  39143. }
  39144. vertexBuffer.updateDirectly(data, offset, useBytes);
  39145. this.notifyUpdate(kind);
  39146. };
  39147. /**
  39148. * Update a specific vertex buffer
  39149. * This function will create a new buffer if the current one is not updatable
  39150. * @param kind defines the data kind (Position, normal, etc...)
  39151. * @param data defines the data to use
  39152. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39153. */
  39154. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39155. if (updateExtends === void 0) { updateExtends = false; }
  39156. var vertexBuffer = this.getVertexBuffer(kind);
  39157. if (!vertexBuffer) {
  39158. return;
  39159. }
  39160. vertexBuffer.update(data);
  39161. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39162. this._updateBoundingInfo(updateExtends, data);
  39163. }
  39164. this.notifyUpdate(kind);
  39165. };
  39166. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39167. if (updateExtends) {
  39168. this._updateExtend(data);
  39169. }
  39170. var meshes = this._meshes;
  39171. var numOfMeshes = meshes.length;
  39172. this._resetPointsArrayCache();
  39173. for (var index = 0; index < numOfMeshes; index++) {
  39174. var mesh = meshes[index];
  39175. if (updateExtends) {
  39176. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39177. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39178. var subMesh = mesh.subMeshes[subIndex];
  39179. subMesh.refreshBoundingInfo();
  39180. }
  39181. }
  39182. }
  39183. };
  39184. /** @hidden */
  39185. Geometry.prototype._bind = function (effect, indexToBind) {
  39186. if (!effect) {
  39187. return;
  39188. }
  39189. if (indexToBind === undefined) {
  39190. indexToBind = this._indexBuffer;
  39191. }
  39192. var vbs = this.getVertexBuffers();
  39193. if (!vbs) {
  39194. return;
  39195. }
  39196. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39197. this._engine.bindBuffers(vbs, indexToBind, effect);
  39198. return;
  39199. }
  39200. // Using VAO
  39201. if (!this._vertexArrayObjects[effect.key]) {
  39202. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39203. }
  39204. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39205. };
  39206. /**
  39207. * Gets total number of vertices
  39208. * @returns the total number of vertices
  39209. */
  39210. Geometry.prototype.getTotalVertices = function () {
  39211. if (!this.isReady()) {
  39212. return 0;
  39213. }
  39214. return this._totalVertices;
  39215. };
  39216. /**
  39217. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39218. * @param kind defines the data kind (Position, normal, etc...)
  39219. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39220. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39221. * @returns a float array containing vertex data
  39222. */
  39223. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39224. var vertexBuffer = this.getVertexBuffer(kind);
  39225. if (!vertexBuffer) {
  39226. return null;
  39227. }
  39228. var data = vertexBuffer.getData();
  39229. if (!data) {
  39230. return null;
  39231. }
  39232. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39233. var count = this._totalVertices * vertexBuffer.getSize();
  39234. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39235. var copy_1 = new Array(count);
  39236. vertexBuffer.forEach(count, function (value, index) {
  39237. copy_1[index] = value;
  39238. });
  39239. return copy_1;
  39240. }
  39241. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39242. if (data instanceof Array) {
  39243. var offset = vertexBuffer.byteOffset / 4;
  39244. return BABYLON.Tools.Slice(data, offset, offset + count);
  39245. }
  39246. else if (data instanceof ArrayBuffer) {
  39247. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39248. }
  39249. else {
  39250. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39251. }
  39252. }
  39253. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39254. return BABYLON.Tools.Slice(data);
  39255. }
  39256. return data;
  39257. };
  39258. /**
  39259. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39260. * @param kind defines the data kind (Position, normal, etc...)
  39261. * @returns true if the vertex buffer with the specified kind is updatable
  39262. */
  39263. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39264. var vb = this._vertexBuffers[kind];
  39265. if (!vb) {
  39266. return false;
  39267. }
  39268. return vb.isUpdatable();
  39269. };
  39270. /**
  39271. * Gets a specific vertex buffer
  39272. * @param kind defines the data kind (Position, normal, etc...)
  39273. * @returns a {BABYLON.VertexBuffer}
  39274. */
  39275. Geometry.prototype.getVertexBuffer = function (kind) {
  39276. if (!this.isReady()) {
  39277. return null;
  39278. }
  39279. return this._vertexBuffers[kind];
  39280. };
  39281. /**
  39282. * Returns all vertex buffers
  39283. * @return an object holding all vertex buffers indexed by kind
  39284. */
  39285. Geometry.prototype.getVertexBuffers = function () {
  39286. if (!this.isReady()) {
  39287. return null;
  39288. }
  39289. return this._vertexBuffers;
  39290. };
  39291. /**
  39292. * Gets a boolean indicating if specific vertex buffer is present
  39293. * @param kind defines the data kind (Position, normal, etc...)
  39294. * @returns true if data is present
  39295. */
  39296. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39297. if (!this._vertexBuffers) {
  39298. if (this._delayInfo) {
  39299. return this._delayInfo.indexOf(kind) !== -1;
  39300. }
  39301. return false;
  39302. }
  39303. return this._vertexBuffers[kind] !== undefined;
  39304. };
  39305. /**
  39306. * Gets a list of all attached data kinds (Position, normal, etc...)
  39307. * @returns a list of string containing all kinds
  39308. */
  39309. Geometry.prototype.getVerticesDataKinds = function () {
  39310. var result = [];
  39311. var kind;
  39312. if (!this._vertexBuffers && this._delayInfo) {
  39313. for (kind in this._delayInfo) {
  39314. result.push(kind);
  39315. }
  39316. }
  39317. else {
  39318. for (kind in this._vertexBuffers) {
  39319. result.push(kind);
  39320. }
  39321. }
  39322. return result;
  39323. };
  39324. /**
  39325. * Update index buffer
  39326. * @param indices defines the indices to store in the index buffer
  39327. * @param offset defines the offset in the target buffer where to store the data
  39328. */
  39329. Geometry.prototype.updateIndices = function (indices, offset) {
  39330. if (!this._indexBuffer) {
  39331. return;
  39332. }
  39333. if (!this._indexBufferIsUpdatable) {
  39334. this.setIndices(indices, null, true);
  39335. }
  39336. else {
  39337. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39338. }
  39339. };
  39340. /**
  39341. * Creates a new index buffer
  39342. * @param indices defines the indices to store in the index buffer
  39343. * @param totalVertices defines the total number of vertices (could be null)
  39344. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39345. */
  39346. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39347. if (totalVertices === void 0) { totalVertices = null; }
  39348. if (updatable === void 0) { updatable = false; }
  39349. if (this._indexBuffer) {
  39350. this._engine._releaseBuffer(this._indexBuffer);
  39351. }
  39352. this._disposeVertexArrayObjects();
  39353. this._indices = indices;
  39354. this._indexBufferIsUpdatable = updatable;
  39355. if (this._meshes.length !== 0 && this._indices) {
  39356. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39357. }
  39358. if (totalVertices != undefined) { // including null and undefined
  39359. this._totalVertices = totalVertices;
  39360. }
  39361. var meshes = this._meshes;
  39362. var numOfMeshes = meshes.length;
  39363. for (var index = 0; index < numOfMeshes; index++) {
  39364. meshes[index]._createGlobalSubMesh(true);
  39365. }
  39366. this.notifyUpdate();
  39367. };
  39368. /**
  39369. * Return the total number of indices
  39370. * @returns the total number of indices
  39371. */
  39372. Geometry.prototype.getTotalIndices = function () {
  39373. if (!this.isReady()) {
  39374. return 0;
  39375. }
  39376. return this._indices.length;
  39377. };
  39378. /**
  39379. * Gets the index buffer array
  39380. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39381. * @returns the index buffer array
  39382. */
  39383. Geometry.prototype.getIndices = function (copyWhenShared) {
  39384. if (!this.isReady()) {
  39385. return null;
  39386. }
  39387. var orig = this._indices;
  39388. if (!copyWhenShared || this._meshes.length === 1) {
  39389. return orig;
  39390. }
  39391. else {
  39392. var len = orig.length;
  39393. var copy = [];
  39394. for (var i = 0; i < len; i++) {
  39395. copy.push(orig[i]);
  39396. }
  39397. return copy;
  39398. }
  39399. };
  39400. /**
  39401. * Gets the index buffer
  39402. * @return the index buffer
  39403. */
  39404. Geometry.prototype.getIndexBuffer = function () {
  39405. if (!this.isReady()) {
  39406. return null;
  39407. }
  39408. return this._indexBuffer;
  39409. };
  39410. /** @hidden */
  39411. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39412. if (effect === void 0) { effect = null; }
  39413. if (!effect || !this._vertexArrayObjects) {
  39414. return;
  39415. }
  39416. if (this._vertexArrayObjects[effect.key]) {
  39417. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39418. delete this._vertexArrayObjects[effect.key];
  39419. }
  39420. };
  39421. /**
  39422. * Release the associated resources for a specific mesh
  39423. * @param mesh defines the source mesh
  39424. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39425. */
  39426. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39427. var meshes = this._meshes;
  39428. var index = meshes.indexOf(mesh);
  39429. if (index === -1) {
  39430. return;
  39431. }
  39432. meshes.splice(index, 1);
  39433. mesh._geometry = null;
  39434. if (meshes.length === 0 && shouldDispose) {
  39435. this.dispose();
  39436. }
  39437. };
  39438. /**
  39439. * Apply current geometry to a given mesh
  39440. * @param mesh defines the mesh to apply geometry to
  39441. */
  39442. Geometry.prototype.applyToMesh = function (mesh) {
  39443. if (mesh._geometry === this) {
  39444. return;
  39445. }
  39446. var previousGeometry = mesh._geometry;
  39447. if (previousGeometry) {
  39448. previousGeometry.releaseForMesh(mesh);
  39449. }
  39450. var meshes = this._meshes;
  39451. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39452. mesh._geometry = this;
  39453. this._scene.pushGeometry(this);
  39454. meshes.push(mesh);
  39455. if (this.isReady()) {
  39456. this._applyToMesh(mesh);
  39457. }
  39458. else {
  39459. mesh._boundingInfo = this._boundingInfo;
  39460. }
  39461. };
  39462. Geometry.prototype._updateExtend = function (data) {
  39463. if (data === void 0) { data = null; }
  39464. if (!data) {
  39465. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39466. }
  39467. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39468. };
  39469. Geometry.prototype._applyToMesh = function (mesh) {
  39470. var numOfMeshes = this._meshes.length;
  39471. // vertexBuffers
  39472. for (var kind in this._vertexBuffers) {
  39473. if (numOfMeshes === 1) {
  39474. this._vertexBuffers[kind].create();
  39475. }
  39476. var buffer = this._vertexBuffers[kind].getBuffer();
  39477. if (buffer)
  39478. buffer.references = numOfMeshes;
  39479. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39480. if (!this._extend) {
  39481. this._updateExtend();
  39482. }
  39483. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39484. mesh._createGlobalSubMesh(false);
  39485. //bounding info was just created again, world matrix should be applied again.
  39486. mesh._updateBoundingInfo();
  39487. }
  39488. }
  39489. // indexBuffer
  39490. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39491. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39492. }
  39493. if (this._indexBuffer) {
  39494. this._indexBuffer.references = numOfMeshes;
  39495. }
  39496. };
  39497. Geometry.prototype.notifyUpdate = function (kind) {
  39498. if (this.onGeometryUpdated) {
  39499. this.onGeometryUpdated(this, kind);
  39500. }
  39501. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39502. var mesh = _a[_i];
  39503. mesh._markSubMeshesAsAttributesDirty();
  39504. }
  39505. };
  39506. /**
  39507. * Load the geometry if it was flagged as delay loaded
  39508. * @param scene defines the hosting scene
  39509. * @param onLoaded defines a callback called when the geometry is loaded
  39510. */
  39511. Geometry.prototype.load = function (scene, onLoaded) {
  39512. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39513. return;
  39514. }
  39515. if (this.isReady()) {
  39516. if (onLoaded) {
  39517. onLoaded();
  39518. }
  39519. return;
  39520. }
  39521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39522. this._queueLoad(scene, onLoaded);
  39523. };
  39524. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39525. var _this = this;
  39526. if (!this.delayLoadingFile) {
  39527. return;
  39528. }
  39529. scene._addPendingData(this);
  39530. scene._loadFile(this.delayLoadingFile, function (data) {
  39531. if (!_this._delayLoadingFunction) {
  39532. return;
  39533. }
  39534. _this._delayLoadingFunction(JSON.parse(data), _this);
  39535. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39536. _this._delayInfo = [];
  39537. scene._removePendingData(_this);
  39538. var meshes = _this._meshes;
  39539. var numOfMeshes = meshes.length;
  39540. for (var index = 0; index < numOfMeshes; index++) {
  39541. _this._applyToMesh(meshes[index]);
  39542. }
  39543. if (onLoaded) {
  39544. onLoaded();
  39545. }
  39546. }, undefined, true);
  39547. };
  39548. /**
  39549. * Invert the geometry to move from a right handed system to a left handed one.
  39550. */
  39551. Geometry.prototype.toLeftHanded = function () {
  39552. // Flip faces
  39553. var tIndices = this.getIndices(false);
  39554. if (tIndices != null && tIndices.length > 0) {
  39555. for (var i = 0; i < tIndices.length; i += 3) {
  39556. var tTemp = tIndices[i + 0];
  39557. tIndices[i + 0] = tIndices[i + 2];
  39558. tIndices[i + 2] = tTemp;
  39559. }
  39560. this.setIndices(tIndices);
  39561. }
  39562. // Negate position.z
  39563. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39564. if (tPositions != null && tPositions.length > 0) {
  39565. for (var i = 0; i < tPositions.length; i += 3) {
  39566. tPositions[i + 2] = -tPositions[i + 2];
  39567. }
  39568. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39569. }
  39570. // Negate normal.z
  39571. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39572. if (tNormals != null && tNormals.length > 0) {
  39573. for (var i = 0; i < tNormals.length; i += 3) {
  39574. tNormals[i + 2] = -tNormals[i + 2];
  39575. }
  39576. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39577. }
  39578. };
  39579. // Cache
  39580. /** @hidden */
  39581. Geometry.prototype._resetPointsArrayCache = function () {
  39582. this._positions = null;
  39583. };
  39584. /** @hidden */
  39585. Geometry.prototype._generatePointsArray = function () {
  39586. if (this._positions)
  39587. return true;
  39588. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39589. if (!data || data.length === 0) {
  39590. return false;
  39591. }
  39592. this._positions = [];
  39593. for (var index = 0; index < data.length; index += 3) {
  39594. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39595. }
  39596. return true;
  39597. };
  39598. /**
  39599. * Gets a value indicating if the geometry is disposed
  39600. * @returns true if the geometry was disposed
  39601. */
  39602. Geometry.prototype.isDisposed = function () {
  39603. return this._isDisposed;
  39604. };
  39605. Geometry.prototype._disposeVertexArrayObjects = function () {
  39606. if (this._vertexArrayObjects) {
  39607. for (var kind in this._vertexArrayObjects) {
  39608. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39609. }
  39610. this._vertexArrayObjects = {};
  39611. }
  39612. };
  39613. /**
  39614. * Free all associated resources
  39615. */
  39616. Geometry.prototype.dispose = function () {
  39617. var meshes = this._meshes;
  39618. var numOfMeshes = meshes.length;
  39619. var index;
  39620. for (index = 0; index < numOfMeshes; index++) {
  39621. this.releaseForMesh(meshes[index]);
  39622. }
  39623. this._meshes = [];
  39624. this._disposeVertexArrayObjects();
  39625. for (var kind in this._vertexBuffers) {
  39626. this._vertexBuffers[kind].dispose();
  39627. }
  39628. this._vertexBuffers = {};
  39629. this._totalVertices = 0;
  39630. if (this._indexBuffer) {
  39631. this._engine._releaseBuffer(this._indexBuffer);
  39632. }
  39633. this._indexBuffer = null;
  39634. this._indices = [];
  39635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39636. this.delayLoadingFile = null;
  39637. this._delayLoadingFunction = null;
  39638. this._delayInfo = [];
  39639. this._boundingInfo = null;
  39640. this._scene.removeGeometry(this);
  39641. this._isDisposed = true;
  39642. };
  39643. /**
  39644. * Clone the current geometry into a new geometry
  39645. * @param id defines the unique ID of the new geometry
  39646. * @returns a new geometry object
  39647. */
  39648. Geometry.prototype.copy = function (id) {
  39649. var vertexData = new BABYLON.VertexData();
  39650. vertexData.indices = [];
  39651. var indices = this.getIndices();
  39652. if (indices) {
  39653. for (var index = 0; index < indices.length; index++) {
  39654. vertexData.indices.push(indices[index]);
  39655. }
  39656. }
  39657. var updatable = false;
  39658. var stopChecking = false;
  39659. var kind;
  39660. for (kind in this._vertexBuffers) {
  39661. // using slice() to make a copy of the array and not just reference it
  39662. var data = this.getVerticesData(kind);
  39663. if (data instanceof Float32Array) {
  39664. vertexData.set(new Float32Array(data), kind);
  39665. }
  39666. else {
  39667. vertexData.set(data.slice(0), kind);
  39668. }
  39669. if (!stopChecking) {
  39670. var vb = this.getVertexBuffer(kind);
  39671. if (vb) {
  39672. updatable = vb.isUpdatable();
  39673. stopChecking = !updatable;
  39674. }
  39675. }
  39676. }
  39677. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39678. geometry.delayLoadState = this.delayLoadState;
  39679. geometry.delayLoadingFile = this.delayLoadingFile;
  39680. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39681. for (kind in this._delayInfo) {
  39682. geometry._delayInfo = geometry._delayInfo || [];
  39683. geometry._delayInfo.push(kind);
  39684. }
  39685. // Bounding info
  39686. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39687. return geometry;
  39688. };
  39689. /**
  39690. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39691. * @return a JSON representation of the current geometry data (without the vertices data)
  39692. */
  39693. Geometry.prototype.serialize = function () {
  39694. var serializationObject = {};
  39695. serializationObject.id = this.id;
  39696. serializationObject.updatable = this._updatable;
  39697. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39698. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39699. }
  39700. return serializationObject;
  39701. };
  39702. Geometry.prototype.toNumberArray = function (origin) {
  39703. if (Array.isArray(origin)) {
  39704. return origin;
  39705. }
  39706. else {
  39707. return Array.prototype.slice.call(origin);
  39708. }
  39709. };
  39710. /**
  39711. * Serialize all vertices data into a JSON oject
  39712. * @returns a JSON representation of the current geometry data
  39713. */
  39714. Geometry.prototype.serializeVerticeData = function () {
  39715. var serializationObject = this.serialize();
  39716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39717. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39718. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39719. serializationObject.positions._updatable = true;
  39720. }
  39721. }
  39722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39723. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39724. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39725. serializationObject.normals._updatable = true;
  39726. }
  39727. }
  39728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39729. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39730. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39731. serializationObject.tangets._updatable = true;
  39732. }
  39733. }
  39734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39735. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39737. serializationObject.uvs._updatable = true;
  39738. }
  39739. }
  39740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39741. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39742. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39743. serializationObject.uv2s._updatable = true;
  39744. }
  39745. }
  39746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39747. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39748. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39749. serializationObject.uv3s._updatable = true;
  39750. }
  39751. }
  39752. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39753. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39754. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39755. serializationObject.uv4s._updatable = true;
  39756. }
  39757. }
  39758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39759. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39760. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39761. serializationObject.uv5s._updatable = true;
  39762. }
  39763. }
  39764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39765. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39766. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39767. serializationObject.uv6s._updatable = true;
  39768. }
  39769. }
  39770. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39771. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39772. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39773. serializationObject.colors._updatable = true;
  39774. }
  39775. }
  39776. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39777. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39778. serializationObject.matricesIndices._isExpanded = true;
  39779. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39780. serializationObject.matricesIndices._updatable = true;
  39781. }
  39782. }
  39783. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39784. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39785. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39786. serializationObject.matricesWeights._updatable = true;
  39787. }
  39788. }
  39789. serializationObject.indices = this.toNumberArray(this.getIndices());
  39790. return serializationObject;
  39791. };
  39792. // Statics
  39793. /**
  39794. * Extracts a clone of a mesh geometry
  39795. * @param mesh defines the source mesh
  39796. * @param id defines the unique ID of the new geometry object
  39797. * @returns the new geometry object
  39798. */
  39799. Geometry.ExtractFromMesh = function (mesh, id) {
  39800. var geometry = mesh._geometry;
  39801. if (!geometry) {
  39802. return null;
  39803. }
  39804. return geometry.copy(id);
  39805. };
  39806. /**
  39807. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39808. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39809. * Be aware Math.random() could cause collisions, but:
  39810. * "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"
  39811. * @returns a string containing a new GUID
  39812. */
  39813. Geometry.RandomId = function () {
  39814. return BABYLON.Tools.RandomId();
  39815. };
  39816. /** @hidden */
  39817. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39818. var scene = mesh.getScene();
  39819. // Geometry
  39820. var geometryId = parsedGeometry.geometryId;
  39821. if (geometryId) {
  39822. var geometry = scene.getGeometryByID(geometryId);
  39823. if (geometry) {
  39824. geometry.applyToMesh(mesh);
  39825. }
  39826. }
  39827. else if (parsedGeometry instanceof ArrayBuffer) {
  39828. var binaryInfo = mesh._binaryInfo;
  39829. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39830. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39832. }
  39833. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39834. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39836. }
  39837. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39838. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39840. }
  39841. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39842. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39843. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39844. }
  39845. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39846. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39847. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39848. }
  39849. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39850. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39851. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39852. }
  39853. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39854. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39855. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39856. }
  39857. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39858. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39859. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39860. }
  39861. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39862. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39864. }
  39865. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39866. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39867. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39868. }
  39869. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39870. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39871. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39872. }
  39873. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39874. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39875. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39876. }
  39877. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39878. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39879. mesh.setIndices(indicesData, null);
  39880. }
  39881. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39882. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39883. mesh.subMeshes = [];
  39884. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39885. var materialIndex = subMeshesData[(i * 5) + 0];
  39886. var verticesStart = subMeshesData[(i * 5) + 1];
  39887. var verticesCount = subMeshesData[(i * 5) + 2];
  39888. var indexStart = subMeshesData[(i * 5) + 3];
  39889. var indexCount = subMeshesData[(i * 5) + 4];
  39890. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39891. }
  39892. }
  39893. }
  39894. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39896. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39897. if (parsedGeometry.tangents) {
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39899. }
  39900. if (parsedGeometry.uvs) {
  39901. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39902. }
  39903. if (parsedGeometry.uvs2) {
  39904. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39905. }
  39906. if (parsedGeometry.uvs3) {
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39908. }
  39909. if (parsedGeometry.uvs4) {
  39910. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39911. }
  39912. if (parsedGeometry.uvs5) {
  39913. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39914. }
  39915. if (parsedGeometry.uvs6) {
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39917. }
  39918. if (parsedGeometry.colors) {
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39920. }
  39921. if (parsedGeometry.matricesIndices) {
  39922. if (!parsedGeometry.matricesIndices._isExpanded) {
  39923. var floatIndices = [];
  39924. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39925. var matricesIndex = parsedGeometry.matricesIndices[i];
  39926. floatIndices.push(matricesIndex & 0x000000FF);
  39927. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39928. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39929. floatIndices.push(matricesIndex >> 24);
  39930. }
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39932. }
  39933. else {
  39934. delete parsedGeometry.matricesIndices._isExpanded;
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39936. }
  39937. }
  39938. if (parsedGeometry.matricesIndicesExtra) {
  39939. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39940. var floatIndices = [];
  39941. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39942. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39943. floatIndices.push(matricesIndex & 0x000000FF);
  39944. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39945. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39946. floatIndices.push(matricesIndex >> 24);
  39947. }
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39949. }
  39950. else {
  39951. delete parsedGeometry.matricesIndices._isExpanded;
  39952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39953. }
  39954. }
  39955. if (parsedGeometry.matricesWeights) {
  39956. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39957. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39958. }
  39959. if (parsedGeometry.matricesWeightsExtra) {
  39960. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39961. }
  39962. mesh.setIndices(parsedGeometry.indices, null);
  39963. }
  39964. // SubMeshes
  39965. if (parsedGeometry.subMeshes) {
  39966. mesh.subMeshes = [];
  39967. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39968. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39969. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39970. }
  39971. }
  39972. // Flat shading
  39973. if (mesh._shouldGenerateFlatShading) {
  39974. mesh.convertToFlatShadedMesh();
  39975. delete mesh._shouldGenerateFlatShading;
  39976. }
  39977. // Update
  39978. mesh.computeWorldMatrix(true);
  39979. // Octree
  39980. var sceneOctree = scene.selectionOctree;
  39981. if (sceneOctree !== undefined && sceneOctree !== null) {
  39982. sceneOctree.addMesh(mesh);
  39983. }
  39984. };
  39985. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39986. var epsilon = 1e-3;
  39987. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39988. return;
  39989. }
  39990. var noInfluenceBoneIndex = 0.0;
  39991. if (parsedGeometry.skeletonId > -1) {
  39992. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39993. if (!skeleton) {
  39994. return;
  39995. }
  39996. noInfluenceBoneIndex = skeleton.bones.length;
  39997. }
  39998. else {
  39999. return;
  40000. }
  40001. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40002. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40003. var matricesWeights = parsedGeometry.matricesWeights;
  40004. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40005. var influencers = parsedGeometry.numBoneInfluencer;
  40006. var size = matricesWeights.length;
  40007. for (var i = 0; i < size; i += 4) {
  40008. var weight = 0.0;
  40009. var firstZeroWeight = -1;
  40010. for (var j = 0; j < 4; j++) {
  40011. var w = matricesWeights[i + j];
  40012. weight += w;
  40013. if (w < epsilon && firstZeroWeight < 0) {
  40014. firstZeroWeight = j;
  40015. }
  40016. }
  40017. if (matricesWeightsExtra) {
  40018. for (var j = 0; j < 4; j++) {
  40019. var w = matricesWeightsExtra[i + j];
  40020. weight += w;
  40021. if (w < epsilon && firstZeroWeight < 0) {
  40022. firstZeroWeight = j + 4;
  40023. }
  40024. }
  40025. }
  40026. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40027. firstZeroWeight = influencers - 1;
  40028. }
  40029. if (weight > epsilon) {
  40030. var mweight = 1.0 / weight;
  40031. for (var j = 0; j < 4; j++) {
  40032. matricesWeights[i + j] *= mweight;
  40033. }
  40034. if (matricesWeightsExtra) {
  40035. for (var j = 0; j < 4; j++) {
  40036. matricesWeightsExtra[i + j] *= mweight;
  40037. }
  40038. }
  40039. }
  40040. else {
  40041. if (firstZeroWeight >= 4) {
  40042. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40043. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40044. }
  40045. else {
  40046. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40047. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40048. }
  40049. }
  40050. }
  40051. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40052. if (parsedGeometry.matricesWeightsExtra) {
  40053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40054. }
  40055. };
  40056. /**
  40057. * Create a new geometry from persisted data (Using .babylon file format)
  40058. * @param parsedVertexData defines the persisted data
  40059. * @param scene defines the hosting scene
  40060. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40061. * @returns the new geometry object
  40062. */
  40063. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40064. if (scene.getGeometryByID(parsedVertexData.id)) {
  40065. return null; // null since geometry could be something else than a box...
  40066. }
  40067. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40068. if (BABYLON.Tags) {
  40069. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40070. }
  40071. if (parsedVertexData.delayLoadingFile) {
  40072. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40073. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40074. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40075. geometry._delayInfo = [];
  40076. if (parsedVertexData.hasUVs) {
  40077. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40078. }
  40079. if (parsedVertexData.hasUVs2) {
  40080. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40081. }
  40082. if (parsedVertexData.hasUVs3) {
  40083. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40084. }
  40085. if (parsedVertexData.hasUVs4) {
  40086. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40087. }
  40088. if (parsedVertexData.hasUVs5) {
  40089. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40090. }
  40091. if (parsedVertexData.hasUVs6) {
  40092. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40093. }
  40094. if (parsedVertexData.hasColors) {
  40095. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40096. }
  40097. if (parsedVertexData.hasMatricesIndices) {
  40098. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40099. }
  40100. if (parsedVertexData.hasMatricesWeights) {
  40101. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40102. }
  40103. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40104. }
  40105. else {
  40106. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40107. }
  40108. scene.pushGeometry(geometry, true);
  40109. return geometry;
  40110. };
  40111. return Geometry;
  40112. }());
  40113. BABYLON.Geometry = Geometry;
  40114. // Primitives
  40115. /// Abstract class
  40116. /**
  40117. * Abstract class used to provide common services for all typed geometries
  40118. * @hidden
  40119. */
  40120. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40121. __extends(_PrimitiveGeometry, _super);
  40122. /**
  40123. * Creates a new typed geometry
  40124. * @param id defines the unique ID of the geometry
  40125. * @param scene defines the hosting scene
  40126. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40127. * @param mesh defines the hosting mesh (can be null)
  40128. */
  40129. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40130. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40131. if (mesh === void 0) { mesh = null; }
  40132. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40133. _this._canBeRegenerated = _canBeRegenerated;
  40134. _this._beingRegenerated = true;
  40135. _this.regenerate();
  40136. _this._beingRegenerated = false;
  40137. return _this;
  40138. }
  40139. /**
  40140. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40141. * @returns true if the geometry can be regenerated
  40142. */
  40143. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40144. return this._canBeRegenerated;
  40145. };
  40146. /**
  40147. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40148. */
  40149. _PrimitiveGeometry.prototype.regenerate = function () {
  40150. if (!this._canBeRegenerated) {
  40151. return;
  40152. }
  40153. this._beingRegenerated = true;
  40154. this.setAllVerticesData(this._regenerateVertexData(), false);
  40155. this._beingRegenerated = false;
  40156. };
  40157. /**
  40158. * Clone the geometry
  40159. * @param id defines the unique ID of the new geometry
  40160. * @returns the new geometry
  40161. */
  40162. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40163. return _super.prototype.copy.call(this, id);
  40164. };
  40165. // overrides
  40166. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40167. if (!this._beingRegenerated) {
  40168. return;
  40169. }
  40170. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40171. };
  40172. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40173. if (!this._beingRegenerated) {
  40174. return;
  40175. }
  40176. _super.prototype.setVerticesData.call(this, kind, data, false);
  40177. };
  40178. // to override
  40179. /** @hidden */
  40180. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40181. throw new Error("Abstract method");
  40182. };
  40183. _PrimitiveGeometry.prototype.copy = function (id) {
  40184. throw new Error("Must be overriden in sub-classes.");
  40185. };
  40186. _PrimitiveGeometry.prototype.serialize = function () {
  40187. var serializationObject = _super.prototype.serialize.call(this);
  40188. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40189. return serializationObject;
  40190. };
  40191. return _PrimitiveGeometry;
  40192. }(Geometry));
  40193. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40194. /**
  40195. * Creates a ribbon geometry
  40196. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40197. */
  40198. var RibbonGeometry = /** @class */ (function (_super) {
  40199. __extends(RibbonGeometry, _super);
  40200. /**
  40201. * Creates a ribbon geometry
  40202. * @param id defines the unique ID of the geometry
  40203. * @param scene defines the hosting scene
  40204. * @param pathArray defines the array of paths to use
  40205. * @param closeArray defines if the last path and the first path must be joined
  40206. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40207. * @param offset defines the offset between points
  40208. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40209. * @param mesh defines the hosting mesh (can be null)
  40210. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40211. */
  40212. function RibbonGeometry(id, scene,
  40213. /**
  40214. * Defines the array of paths to use
  40215. */
  40216. pathArray,
  40217. /**
  40218. * Defines if the last and first points of each path in your pathArray must be joined
  40219. */
  40220. closeArray,
  40221. /**
  40222. * Defines if the last and first points of each path in your pathArray must be joined
  40223. */
  40224. closePath,
  40225. /**
  40226. * Defines the offset between points
  40227. */
  40228. offset, canBeRegenerated, mesh,
  40229. /**
  40230. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40231. */
  40232. side) {
  40233. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40234. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40235. _this.pathArray = pathArray;
  40236. _this.closeArray = closeArray;
  40237. _this.closePath = closePath;
  40238. _this.offset = offset;
  40239. _this.side = side;
  40240. return _this;
  40241. }
  40242. /** @hidden */
  40243. RibbonGeometry.prototype._regenerateVertexData = function () {
  40244. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40245. };
  40246. RibbonGeometry.prototype.copy = function (id) {
  40247. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40248. };
  40249. return RibbonGeometry;
  40250. }(_PrimitiveGeometry));
  40251. BABYLON.RibbonGeometry = RibbonGeometry;
  40252. /**
  40253. * Creates a box geometry
  40254. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40255. */
  40256. var BoxGeometry = /** @class */ (function (_super) {
  40257. __extends(BoxGeometry, _super);
  40258. /**
  40259. * Creates a box geometry
  40260. * @param id defines the unique ID of the geometry
  40261. * @param scene defines the hosting scene
  40262. * @param size defines the zise of the box (width, height and depth are the same)
  40263. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40264. * @param mesh defines the hosting mesh (can be null)
  40265. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40266. */
  40267. function BoxGeometry(id, scene,
  40268. /**
  40269. * Defines the zise of the box (width, height and depth are the same)
  40270. */
  40271. size, canBeRegenerated, mesh,
  40272. /**
  40273. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40274. */
  40275. side) {
  40276. if (mesh === void 0) { mesh = null; }
  40277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40278. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40279. _this.size = size;
  40280. _this.side = side;
  40281. return _this;
  40282. }
  40283. BoxGeometry.prototype._regenerateVertexData = function () {
  40284. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40285. };
  40286. BoxGeometry.prototype.copy = function (id) {
  40287. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40288. };
  40289. BoxGeometry.prototype.serialize = function () {
  40290. var serializationObject = _super.prototype.serialize.call(this);
  40291. serializationObject.size = this.size;
  40292. return serializationObject;
  40293. };
  40294. BoxGeometry.Parse = function (parsedBox, scene) {
  40295. if (scene.getGeometryByID(parsedBox.id)) {
  40296. return null; // null since geometry could be something else than a box...
  40297. }
  40298. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40299. if (BABYLON.Tags) {
  40300. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40301. }
  40302. scene.pushGeometry(box, true);
  40303. return box;
  40304. };
  40305. return BoxGeometry;
  40306. }(_PrimitiveGeometry));
  40307. BABYLON.BoxGeometry = BoxGeometry;
  40308. /**
  40309. * Creates a sphere geometry
  40310. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40311. */
  40312. var SphereGeometry = /** @class */ (function (_super) {
  40313. __extends(SphereGeometry, _super);
  40314. /**
  40315. * Create a new sphere geometry
  40316. * @param id defines the unique ID of the geometry
  40317. * @param scene defines the hosting scene
  40318. * @param segments defines the number of segments to use to create the sphere
  40319. * @param diameter defines the diameter of the sphere
  40320. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40321. * @param mesh defines the hosting mesh (can be null)
  40322. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40323. */
  40324. function SphereGeometry(id, scene,
  40325. /**
  40326. * Defines the number of segments to use to create the sphere
  40327. */
  40328. segments,
  40329. /**
  40330. * Defines the diameter of the sphere
  40331. */
  40332. diameter, canBeRegenerated, mesh,
  40333. /**
  40334. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40335. */
  40336. side) {
  40337. if (mesh === void 0) { mesh = null; }
  40338. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40339. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40340. _this.segments = segments;
  40341. _this.diameter = diameter;
  40342. _this.side = side;
  40343. return _this;
  40344. }
  40345. SphereGeometry.prototype._regenerateVertexData = function () {
  40346. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40347. };
  40348. SphereGeometry.prototype.copy = function (id) {
  40349. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40350. };
  40351. SphereGeometry.prototype.serialize = function () {
  40352. var serializationObject = _super.prototype.serialize.call(this);
  40353. serializationObject.segments = this.segments;
  40354. serializationObject.diameter = this.diameter;
  40355. return serializationObject;
  40356. };
  40357. SphereGeometry.Parse = function (parsedSphere, scene) {
  40358. if (scene.getGeometryByID(parsedSphere.id)) {
  40359. return null; // null since geometry could be something else than a sphere...
  40360. }
  40361. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40362. if (BABYLON.Tags) {
  40363. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40364. }
  40365. scene.pushGeometry(sphere, true);
  40366. return sphere;
  40367. };
  40368. return SphereGeometry;
  40369. }(_PrimitiveGeometry));
  40370. BABYLON.SphereGeometry = SphereGeometry;
  40371. /**
  40372. * Creates a disc geometry
  40373. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40374. */
  40375. var DiscGeometry = /** @class */ (function (_super) {
  40376. __extends(DiscGeometry, _super);
  40377. /**
  40378. * Creates a new disc geometry
  40379. * @param id defines the unique ID of the geometry
  40380. * @param scene defines the hosting scene
  40381. * @param radius defines the radius of the disc
  40382. * @param tessellation defines the tesselation factor to apply to the disc
  40383. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40384. * @param mesh defines the hosting mesh (can be null)
  40385. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40386. */
  40387. function DiscGeometry(id, scene,
  40388. /**
  40389. * Defines the radius of the disc
  40390. */
  40391. radius,
  40392. /**
  40393. * Defines the tesselation factor to apply to the disc
  40394. */
  40395. tessellation, canBeRegenerated, mesh,
  40396. /**
  40397. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40398. */
  40399. side) {
  40400. if (mesh === void 0) { mesh = null; }
  40401. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40402. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40403. _this.radius = radius;
  40404. _this.tessellation = tessellation;
  40405. _this.side = side;
  40406. return _this;
  40407. }
  40408. DiscGeometry.prototype._regenerateVertexData = function () {
  40409. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40410. };
  40411. DiscGeometry.prototype.copy = function (id) {
  40412. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40413. };
  40414. return DiscGeometry;
  40415. }(_PrimitiveGeometry));
  40416. BABYLON.DiscGeometry = DiscGeometry;
  40417. /**
  40418. * Creates a new cylinder geometry
  40419. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40420. */
  40421. var CylinderGeometry = /** @class */ (function (_super) {
  40422. __extends(CylinderGeometry, _super);
  40423. /**
  40424. * Creates a new cylinder geometry
  40425. * @param id defines the unique ID of the geometry
  40426. * @param scene defines the hosting scene
  40427. * @param height defines the height of the cylinder
  40428. * @param diameterTop defines the diameter of the cylinder's top cap
  40429. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40430. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40431. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40432. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40433. * @param mesh defines the hosting mesh (can be null)
  40434. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40435. */
  40436. function CylinderGeometry(id, scene,
  40437. /**
  40438. * Defines the height of the cylinder
  40439. */
  40440. height,
  40441. /**
  40442. * Defines the diameter of the cylinder's top cap
  40443. */
  40444. diameterTop,
  40445. /**
  40446. * Defines the diameter of the cylinder's bottom cap
  40447. */
  40448. diameterBottom,
  40449. /**
  40450. * Defines the tessellation factor to apply to the cylinder
  40451. */
  40452. tessellation,
  40453. /**
  40454. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40455. */
  40456. subdivisions, canBeRegenerated, mesh,
  40457. /**
  40458. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40459. */
  40460. side) {
  40461. if (subdivisions === void 0) { subdivisions = 1; }
  40462. if (mesh === void 0) { mesh = null; }
  40463. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40464. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40465. _this.height = height;
  40466. _this.diameterTop = diameterTop;
  40467. _this.diameterBottom = diameterBottom;
  40468. _this.tessellation = tessellation;
  40469. _this.subdivisions = subdivisions;
  40470. _this.side = side;
  40471. return _this;
  40472. }
  40473. CylinderGeometry.prototype._regenerateVertexData = function () {
  40474. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40475. };
  40476. CylinderGeometry.prototype.copy = function (id) {
  40477. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40478. };
  40479. CylinderGeometry.prototype.serialize = function () {
  40480. var serializationObject = _super.prototype.serialize.call(this);
  40481. serializationObject.height = this.height;
  40482. serializationObject.diameterTop = this.diameterTop;
  40483. serializationObject.diameterBottom = this.diameterBottom;
  40484. serializationObject.tessellation = this.tessellation;
  40485. return serializationObject;
  40486. };
  40487. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40488. if (scene.getGeometryByID(parsedCylinder.id)) {
  40489. return null; // null since geometry could be something else than a cylinder...
  40490. }
  40491. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40492. if (BABYLON.Tags) {
  40493. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40494. }
  40495. scene.pushGeometry(cylinder, true);
  40496. return cylinder;
  40497. };
  40498. return CylinderGeometry;
  40499. }(_PrimitiveGeometry));
  40500. BABYLON.CylinderGeometry = CylinderGeometry;
  40501. /**
  40502. * Creates a new torus geometry
  40503. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40504. */
  40505. var TorusGeometry = /** @class */ (function (_super) {
  40506. __extends(TorusGeometry, _super);
  40507. /**
  40508. * Creates a new torus geometry
  40509. * @param id defines the unique ID of the geometry
  40510. * @param scene defines the hosting scene
  40511. * @param diameter defines the diameter of the torus
  40512. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40513. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40514. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40515. * @param mesh defines the hosting mesh (can be null)
  40516. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40517. */
  40518. function TorusGeometry(id, scene,
  40519. /**
  40520. * Defines the diameter of the torus
  40521. */
  40522. diameter,
  40523. /**
  40524. * Defines the thickness of the torus (ie. internal diameter)
  40525. */
  40526. thickness,
  40527. /**
  40528. * Defines the tesselation factor to apply to the torus
  40529. */
  40530. tessellation, canBeRegenerated, mesh,
  40531. /**
  40532. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40533. */
  40534. side) {
  40535. if (mesh === void 0) { mesh = null; }
  40536. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40537. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40538. _this.diameter = diameter;
  40539. _this.thickness = thickness;
  40540. _this.tessellation = tessellation;
  40541. _this.side = side;
  40542. return _this;
  40543. }
  40544. TorusGeometry.prototype._regenerateVertexData = function () {
  40545. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40546. };
  40547. TorusGeometry.prototype.copy = function (id) {
  40548. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40549. };
  40550. TorusGeometry.prototype.serialize = function () {
  40551. var serializationObject = _super.prototype.serialize.call(this);
  40552. serializationObject.diameter = this.diameter;
  40553. serializationObject.thickness = this.thickness;
  40554. serializationObject.tessellation = this.tessellation;
  40555. return serializationObject;
  40556. };
  40557. TorusGeometry.Parse = function (parsedTorus, scene) {
  40558. if (scene.getGeometryByID(parsedTorus.id)) {
  40559. return null; // null since geometry could be something else than a torus...
  40560. }
  40561. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40562. if (BABYLON.Tags) {
  40563. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40564. }
  40565. scene.pushGeometry(torus, true);
  40566. return torus;
  40567. };
  40568. return TorusGeometry;
  40569. }(_PrimitiveGeometry));
  40570. BABYLON.TorusGeometry = TorusGeometry;
  40571. /**
  40572. * Creates a new ground geometry
  40573. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40574. */
  40575. var GroundGeometry = /** @class */ (function (_super) {
  40576. __extends(GroundGeometry, _super);
  40577. /**
  40578. * Creates a new ground geometry
  40579. * @param id defines the unique ID of the geometry
  40580. * @param scene defines the hosting scene
  40581. * @param width defines the width of the ground
  40582. * @param height defines the height of the ground
  40583. * @param subdivisions defines the subdivisions to apply to the ground
  40584. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40585. * @param mesh defines the hosting mesh (can be null)
  40586. */
  40587. function GroundGeometry(id, scene,
  40588. /**
  40589. * Defines the width of the ground
  40590. */
  40591. width,
  40592. /**
  40593. * Defines the height of the ground
  40594. */
  40595. height,
  40596. /**
  40597. * Defines the subdivisions to apply to the ground
  40598. */
  40599. subdivisions, canBeRegenerated, mesh) {
  40600. if (mesh === void 0) { mesh = null; }
  40601. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40602. _this.width = width;
  40603. _this.height = height;
  40604. _this.subdivisions = subdivisions;
  40605. return _this;
  40606. }
  40607. GroundGeometry.prototype._regenerateVertexData = function () {
  40608. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40609. };
  40610. GroundGeometry.prototype.copy = function (id) {
  40611. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40612. };
  40613. GroundGeometry.prototype.serialize = function () {
  40614. var serializationObject = _super.prototype.serialize.call(this);
  40615. serializationObject.width = this.width;
  40616. serializationObject.height = this.height;
  40617. serializationObject.subdivisions = this.subdivisions;
  40618. return serializationObject;
  40619. };
  40620. GroundGeometry.Parse = function (parsedGround, scene) {
  40621. if (scene.getGeometryByID(parsedGround.id)) {
  40622. return null; // null since geometry could be something else than a ground...
  40623. }
  40624. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40625. if (BABYLON.Tags) {
  40626. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40627. }
  40628. scene.pushGeometry(ground, true);
  40629. return ground;
  40630. };
  40631. return GroundGeometry;
  40632. }(_PrimitiveGeometry));
  40633. BABYLON.GroundGeometry = GroundGeometry;
  40634. /**
  40635. * Creates a tiled ground geometry
  40636. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40637. */
  40638. var TiledGroundGeometry = /** @class */ (function (_super) {
  40639. __extends(TiledGroundGeometry, _super);
  40640. /**
  40641. * Creates a tiled ground geometry
  40642. * @param id defines the unique ID of the geometry
  40643. * @param scene defines the hosting scene
  40644. * @param xmin defines the minimum value on X axis
  40645. * @param zmin defines the minimum value on Z axis
  40646. * @param xmax defines the maximum value on X axis
  40647. * @param zmax defines the maximum value on Z axis
  40648. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40649. * @param precision defines the precision to use when computing the tiles
  40650. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40651. * @param mesh defines the hosting mesh (can be null)
  40652. */
  40653. function TiledGroundGeometry(id, scene,
  40654. /**
  40655. * Defines the minimum value on X axis
  40656. */
  40657. xmin,
  40658. /**
  40659. * Defines the minimum value on Z axis
  40660. */
  40661. zmin,
  40662. /**
  40663. * Defines the maximum value on X axis
  40664. */
  40665. xmax,
  40666. /**
  40667. * Defines the maximum value on Z axis
  40668. */
  40669. zmax,
  40670. /**
  40671. * Defines the subdivisions to apply to the ground
  40672. */
  40673. subdivisions,
  40674. /**
  40675. * Defines the precision to use when computing the tiles
  40676. */
  40677. precision, canBeRegenerated, mesh) {
  40678. if (mesh === void 0) { mesh = null; }
  40679. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40680. _this.xmin = xmin;
  40681. _this.zmin = zmin;
  40682. _this.xmax = xmax;
  40683. _this.zmax = zmax;
  40684. _this.subdivisions = subdivisions;
  40685. _this.precision = precision;
  40686. return _this;
  40687. }
  40688. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40689. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40690. };
  40691. TiledGroundGeometry.prototype.copy = function (id) {
  40692. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40693. };
  40694. return TiledGroundGeometry;
  40695. }(_PrimitiveGeometry));
  40696. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40697. /**
  40698. * Creates a plane geometry
  40699. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40700. */
  40701. var PlaneGeometry = /** @class */ (function (_super) {
  40702. __extends(PlaneGeometry, _super);
  40703. /**
  40704. * Creates a plane geometry
  40705. * @param id defines the unique ID of the geometry
  40706. * @param scene defines the hosting scene
  40707. * @param size defines the size of the plane (width === height)
  40708. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40709. * @param mesh defines the hosting mesh (can be null)
  40710. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40711. */
  40712. function PlaneGeometry(id, scene,
  40713. /**
  40714. * Defines the size of the plane (width === height)
  40715. */
  40716. size, canBeRegenerated, mesh,
  40717. /**
  40718. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40719. */
  40720. side) {
  40721. if (mesh === void 0) { mesh = null; }
  40722. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40723. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40724. _this.size = size;
  40725. _this.side = side;
  40726. return _this;
  40727. }
  40728. PlaneGeometry.prototype._regenerateVertexData = function () {
  40729. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40730. };
  40731. PlaneGeometry.prototype.copy = function (id) {
  40732. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40733. };
  40734. PlaneGeometry.prototype.serialize = function () {
  40735. var serializationObject = _super.prototype.serialize.call(this);
  40736. serializationObject.size = this.size;
  40737. return serializationObject;
  40738. };
  40739. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40740. if (scene.getGeometryByID(parsedPlane.id)) {
  40741. return null; // null since geometry could be something else than a ground...
  40742. }
  40743. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40744. if (BABYLON.Tags) {
  40745. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40746. }
  40747. scene.pushGeometry(plane, true);
  40748. return plane;
  40749. };
  40750. return PlaneGeometry;
  40751. }(_PrimitiveGeometry));
  40752. BABYLON.PlaneGeometry = PlaneGeometry;
  40753. /**
  40754. * Creates a torus knot geometry
  40755. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40756. */
  40757. var TorusKnotGeometry = /** @class */ (function (_super) {
  40758. __extends(TorusKnotGeometry, _super);
  40759. /**
  40760. * Creates a torus knot geometry
  40761. * @param id defines the unique ID of the geometry
  40762. * @param scene defines the hosting scene
  40763. * @param radius defines the radius of the torus knot
  40764. * @param tube defines the thickness of the torus knot tube
  40765. * @param radialSegments defines the number of radial segments
  40766. * @param tubularSegments defines the number of tubular segments
  40767. * @param p defines the first number of windings
  40768. * @param q defines the second number of windings
  40769. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40770. * @param mesh defines the hosting mesh (can be null)
  40771. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40772. */
  40773. function TorusKnotGeometry(id, scene,
  40774. /**
  40775. * Defines the radius of the torus knot
  40776. */
  40777. radius,
  40778. /**
  40779. * Defines the thickness of the torus knot tube
  40780. */
  40781. tube,
  40782. /**
  40783. * Defines the number of radial segments
  40784. */
  40785. radialSegments,
  40786. /**
  40787. * Defines the number of tubular segments
  40788. */
  40789. tubularSegments,
  40790. /**
  40791. * Defines the first number of windings
  40792. */
  40793. p,
  40794. /**
  40795. * Defines the second number of windings
  40796. */
  40797. q, canBeRegenerated, mesh,
  40798. /**
  40799. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40800. */
  40801. side) {
  40802. if (mesh === void 0) { mesh = null; }
  40803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40805. _this.radius = radius;
  40806. _this.tube = tube;
  40807. _this.radialSegments = radialSegments;
  40808. _this.tubularSegments = tubularSegments;
  40809. _this.p = p;
  40810. _this.q = q;
  40811. _this.side = side;
  40812. return _this;
  40813. }
  40814. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40815. 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 });
  40816. };
  40817. TorusKnotGeometry.prototype.copy = function (id) {
  40818. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40819. };
  40820. TorusKnotGeometry.prototype.serialize = function () {
  40821. var serializationObject = _super.prototype.serialize.call(this);
  40822. serializationObject.radius = this.radius;
  40823. serializationObject.tube = this.tube;
  40824. serializationObject.radialSegments = this.radialSegments;
  40825. serializationObject.tubularSegments = this.tubularSegments;
  40826. serializationObject.p = this.p;
  40827. serializationObject.q = this.q;
  40828. return serializationObject;
  40829. };
  40830. ;
  40831. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40832. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40833. return null; // null since geometry could be something else than a ground...
  40834. }
  40835. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40836. if (BABYLON.Tags) {
  40837. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40838. }
  40839. scene.pushGeometry(torusKnot, true);
  40840. return torusKnot;
  40841. };
  40842. return TorusKnotGeometry;
  40843. }(_PrimitiveGeometry));
  40844. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40845. //}
  40846. })(BABYLON || (BABYLON = {}));
  40847. //# sourceMappingURL=babylon.geometry.js.map
  40848. var BABYLON;
  40849. (function (BABYLON) {
  40850. /**
  40851. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40852. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40853. */
  40854. var PostProcessManager = /** @class */ (function () {
  40855. /**
  40856. * Creates a new instance PostProcess
  40857. * @param scene The scene that the post process is associated with.
  40858. */
  40859. function PostProcessManager(scene) {
  40860. this._vertexBuffers = {};
  40861. this._scene = scene;
  40862. }
  40863. PostProcessManager.prototype._prepareBuffers = function () {
  40864. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40865. return;
  40866. }
  40867. // VBO
  40868. var vertices = [];
  40869. vertices.push(1, 1);
  40870. vertices.push(-1, 1);
  40871. vertices.push(-1, -1);
  40872. vertices.push(1, -1);
  40873. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40874. this._buildIndexBuffer();
  40875. };
  40876. PostProcessManager.prototype._buildIndexBuffer = function () {
  40877. // Indices
  40878. var indices = [];
  40879. indices.push(0);
  40880. indices.push(1);
  40881. indices.push(2);
  40882. indices.push(0);
  40883. indices.push(2);
  40884. indices.push(3);
  40885. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40886. };
  40887. /**
  40888. * Rebuilds the vertex buffers of the manager.
  40889. */
  40890. PostProcessManager.prototype._rebuild = function () {
  40891. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40892. if (!vb) {
  40893. return;
  40894. }
  40895. vb._rebuild();
  40896. this._buildIndexBuffer();
  40897. };
  40898. // Methods
  40899. /**
  40900. * Prepares a frame to be run through a post process.
  40901. * @param sourceTexture The input texture to the post procesess. (default: null)
  40902. * @param postProcesses An array of post processes to be run. (default: null)
  40903. * @returns True if the post processes were able to be run.
  40904. */
  40905. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40906. if (sourceTexture === void 0) { sourceTexture = null; }
  40907. if (postProcesses === void 0) { postProcesses = null; }
  40908. var camera = this._scene.activeCamera;
  40909. if (!camera) {
  40910. return false;
  40911. }
  40912. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40913. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40914. return false;
  40915. }
  40916. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40917. return true;
  40918. };
  40919. /**
  40920. * Manually render a set of post processes to a texture.
  40921. * @param postProcesses An array of post processes to be run.
  40922. * @param targetTexture The target texture to render to.
  40923. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40924. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  40925. * @param lodLevel defines which lod of the texture to render to
  40926. */
  40927. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  40928. if (targetTexture === void 0) { targetTexture = null; }
  40929. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40930. if (faceIndex === void 0) { faceIndex = 0; }
  40931. if (lodLevel === void 0) { lodLevel = 0; }
  40932. var engine = this._scene.getEngine();
  40933. for (var index = 0; index < postProcesses.length; index++) {
  40934. if (index < postProcesses.length - 1) {
  40935. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40936. }
  40937. else {
  40938. if (targetTexture) {
  40939. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  40940. }
  40941. else {
  40942. engine.restoreDefaultFramebuffer();
  40943. }
  40944. }
  40945. var pp = postProcesses[index];
  40946. var effect = pp.apply();
  40947. if (effect) {
  40948. pp.onBeforeRenderObservable.notifyObservers(effect);
  40949. // VBOs
  40950. this._prepareBuffers();
  40951. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40952. // Draw order
  40953. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40954. pp.onAfterRenderObservable.notifyObservers(effect);
  40955. }
  40956. }
  40957. // Restore depth buffer
  40958. engine.setDepthBuffer(true);
  40959. engine.setDepthWrite(true);
  40960. };
  40961. /**
  40962. * Finalize the result of the output of the postprocesses.
  40963. * @param doNotPresent If true the result will not be displayed to the screen.
  40964. * @param targetTexture The target texture to render to.
  40965. * @param faceIndex The index of the face to bind the target texture to.
  40966. * @param postProcesses The array of post processes to render.
  40967. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40968. */
  40969. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40970. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40971. var camera = this._scene.activeCamera;
  40972. if (!camera) {
  40973. return;
  40974. }
  40975. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40976. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40977. return;
  40978. }
  40979. var engine = this._scene.getEngine();
  40980. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40981. var pp = postProcesses[index];
  40982. if (index < len - 1) {
  40983. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40984. }
  40985. else {
  40986. if (targetTexture) {
  40987. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40988. pp._outputTexture = targetTexture;
  40989. }
  40990. else {
  40991. engine.restoreDefaultFramebuffer();
  40992. pp._outputTexture = null;
  40993. }
  40994. }
  40995. if (doNotPresent) {
  40996. break;
  40997. }
  40998. var effect = pp.apply();
  40999. if (effect) {
  41000. pp.onBeforeRenderObservable.notifyObservers(effect);
  41001. // VBOs
  41002. this._prepareBuffers();
  41003. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41004. // Draw order
  41005. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41006. pp.onAfterRenderObservable.notifyObservers(effect);
  41007. }
  41008. }
  41009. // Restore states
  41010. engine.setDepthBuffer(true);
  41011. engine.setDepthWrite(true);
  41012. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41013. };
  41014. /**
  41015. * Disposes of the post process manager.
  41016. */
  41017. PostProcessManager.prototype.dispose = function () {
  41018. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41019. if (buffer) {
  41020. buffer.dispose();
  41021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41022. }
  41023. if (this._indexBuffer) {
  41024. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41025. this._indexBuffer = null;
  41026. }
  41027. };
  41028. return PostProcessManager;
  41029. }());
  41030. BABYLON.PostProcessManager = PostProcessManager;
  41031. })(BABYLON || (BABYLON = {}));
  41032. //# sourceMappingURL=babylon.postProcessManager.js.map
  41033. var BABYLON;
  41034. (function (BABYLON) {
  41035. /**
  41036. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41037. */
  41038. var PerformanceMonitor = /** @class */ (function () {
  41039. /**
  41040. * constructor
  41041. * @param frameSampleSize The number of samples required to saturate the sliding window
  41042. */
  41043. function PerformanceMonitor(frameSampleSize) {
  41044. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41045. this._enabled = true;
  41046. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41047. }
  41048. /**
  41049. * Samples current frame
  41050. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41051. */
  41052. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41053. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41054. if (!this._enabled)
  41055. return;
  41056. if (this._lastFrameTimeMs != null) {
  41057. var dt = timeMs - this._lastFrameTimeMs;
  41058. this._rollingFrameTime.add(dt);
  41059. }
  41060. this._lastFrameTimeMs = timeMs;
  41061. };
  41062. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41063. /**
  41064. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41065. * @return Average frame time in milliseconds
  41066. */
  41067. get: function () {
  41068. return this._rollingFrameTime.average;
  41069. },
  41070. enumerable: true,
  41071. configurable: true
  41072. });
  41073. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41074. /**
  41075. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41076. * @return Frame time variance in milliseconds squared
  41077. */
  41078. get: function () {
  41079. return this._rollingFrameTime.variance;
  41080. },
  41081. enumerable: true,
  41082. configurable: true
  41083. });
  41084. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41085. /**
  41086. * Returns the frame time of the most recent frame
  41087. * @return Frame time in milliseconds
  41088. */
  41089. get: function () {
  41090. return this._rollingFrameTime.history(0);
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41096. /**
  41097. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41098. * @return Framerate in frames per second
  41099. */
  41100. get: function () {
  41101. return 1000.0 / this._rollingFrameTime.average;
  41102. },
  41103. enumerable: true,
  41104. configurable: true
  41105. });
  41106. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41107. /**
  41108. * Returns the average framerate in frames per second using the most recent frame time
  41109. * @return Framerate in frames per second
  41110. */
  41111. get: function () {
  41112. var history = this._rollingFrameTime.history(0);
  41113. if (history === 0) {
  41114. return 0;
  41115. }
  41116. return 1000.0 / history;
  41117. },
  41118. enumerable: true,
  41119. configurable: true
  41120. });
  41121. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41122. /**
  41123. * Returns true if enough samples have been taken to completely fill the sliding window
  41124. * @return true if saturated
  41125. */
  41126. get: function () {
  41127. return this._rollingFrameTime.isSaturated();
  41128. },
  41129. enumerable: true,
  41130. configurable: true
  41131. });
  41132. /**
  41133. * Enables contributions to the sliding window sample set
  41134. */
  41135. PerformanceMonitor.prototype.enable = function () {
  41136. this._enabled = true;
  41137. };
  41138. /**
  41139. * Disables contributions to the sliding window sample set
  41140. * Samples will not be interpolated over the disabled period
  41141. */
  41142. PerformanceMonitor.prototype.disable = function () {
  41143. this._enabled = false;
  41144. //clear last sample to avoid interpolating over the disabled period when next enabled
  41145. this._lastFrameTimeMs = null;
  41146. };
  41147. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41148. /**
  41149. * Returns true if sampling is enabled
  41150. * @return true if enabled
  41151. */
  41152. get: function () {
  41153. return this._enabled;
  41154. },
  41155. enumerable: true,
  41156. configurable: true
  41157. });
  41158. /**
  41159. * Resets performance monitor
  41160. */
  41161. PerformanceMonitor.prototype.reset = function () {
  41162. //clear last sample to avoid interpolating over the disabled period when next enabled
  41163. this._lastFrameTimeMs = null;
  41164. //wipe record
  41165. this._rollingFrameTime.reset();
  41166. };
  41167. return PerformanceMonitor;
  41168. }());
  41169. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41170. /**
  41171. * RollingAverage
  41172. *
  41173. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41174. */
  41175. var RollingAverage = /** @class */ (function () {
  41176. /**
  41177. * constructor
  41178. * @param length The number of samples required to saturate the sliding window
  41179. */
  41180. function RollingAverage(length) {
  41181. this._samples = new Array(length);
  41182. this.reset();
  41183. }
  41184. /**
  41185. * Adds a sample to the sample set
  41186. * @param v The sample value
  41187. */
  41188. RollingAverage.prototype.add = function (v) {
  41189. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41190. var delta;
  41191. //we need to check if we've already wrapped round
  41192. if (this.isSaturated()) {
  41193. //remove bottom of stack from mean
  41194. var bottomValue = this._samples[this._pos];
  41195. delta = bottomValue - this.average;
  41196. this.average -= delta / (this._sampleCount - 1);
  41197. this._m2 -= delta * (bottomValue - this.average);
  41198. }
  41199. else {
  41200. this._sampleCount++;
  41201. }
  41202. //add new value to mean
  41203. delta = v - this.average;
  41204. this.average += delta / (this._sampleCount);
  41205. this._m2 += delta * (v - this.average);
  41206. //set the new variance
  41207. this.variance = this._m2 / (this._sampleCount - 1);
  41208. this._samples[this._pos] = v;
  41209. this._pos++;
  41210. this._pos %= this._samples.length; //positive wrap around
  41211. };
  41212. /**
  41213. * Returns previously added values or null if outside of history or outside the sliding window domain
  41214. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41215. * @return Value previously recorded with add() or null if outside of range
  41216. */
  41217. RollingAverage.prototype.history = function (i) {
  41218. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41219. return 0;
  41220. }
  41221. var i0 = this._wrapPosition(this._pos - 1.0);
  41222. return this._samples[this._wrapPosition(i0 - i)];
  41223. };
  41224. /**
  41225. * Returns true if enough samples have been taken to completely fill the sliding window
  41226. * @return true if sample-set saturated
  41227. */
  41228. RollingAverage.prototype.isSaturated = function () {
  41229. return this._sampleCount >= this._samples.length;
  41230. };
  41231. /**
  41232. * Resets the rolling average (equivalent to 0 samples taken so far)
  41233. */
  41234. RollingAverage.prototype.reset = function () {
  41235. this.average = 0;
  41236. this.variance = 0;
  41237. this._sampleCount = 0;
  41238. this._pos = 0;
  41239. this._m2 = 0;
  41240. };
  41241. /**
  41242. * Wraps a value around the sample range boundaries
  41243. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41244. * @return Wrapped position in sample range
  41245. */
  41246. RollingAverage.prototype._wrapPosition = function (i) {
  41247. var max = this._samples.length;
  41248. return ((i % max) + max) % max;
  41249. };
  41250. return RollingAverage;
  41251. }());
  41252. BABYLON.RollingAverage = RollingAverage;
  41253. })(BABYLON || (BABYLON = {}));
  41254. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41255. var BABYLON;
  41256. (function (BABYLON) {
  41257. /**
  41258. * This groups together the common properties used for image processing either in direct forward pass
  41259. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41260. * or not.
  41261. */
  41262. var ImageProcessingConfiguration = /** @class */ (function () {
  41263. function ImageProcessingConfiguration() {
  41264. /**
  41265. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41266. */
  41267. this.colorCurves = new BABYLON.ColorCurves();
  41268. this._colorCurvesEnabled = false;
  41269. this._colorGradingEnabled = false;
  41270. this._colorGradingWithGreenDepth = true;
  41271. this._colorGradingBGR = true;
  41272. this._exposure = 1.0;
  41273. this._toneMappingEnabled = false;
  41274. this._contrast = 1.0;
  41275. /**
  41276. * Vignette stretch size.
  41277. */
  41278. this.vignetteStretch = 0;
  41279. /**
  41280. * Vignette centre X Offset.
  41281. */
  41282. this.vignetteCentreX = 0;
  41283. /**
  41284. * Vignette centre Y Offset.
  41285. */
  41286. this.vignetteCentreY = 0;
  41287. /**
  41288. * Vignette weight or intensity of the vignette effect.
  41289. */
  41290. this.vignetteWeight = 1.5;
  41291. /**
  41292. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41293. * if vignetteEnabled is set to true.
  41294. */
  41295. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41296. /**
  41297. * Camera field of view used by the Vignette effect.
  41298. */
  41299. this.vignetteCameraFov = 0.5;
  41300. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41301. this._vignetteEnabled = false;
  41302. this._applyByPostProcess = false;
  41303. this._isEnabled = true;
  41304. /**
  41305. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41306. */
  41307. this.onUpdateParameters = new BABYLON.Observable();
  41308. }
  41309. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41310. /**
  41311. * Gets wether the color curves effect is enabled.
  41312. */
  41313. get: function () {
  41314. return this._colorCurvesEnabled;
  41315. },
  41316. /**
  41317. * Sets wether the color curves effect is enabled.
  41318. */
  41319. set: function (value) {
  41320. if (this._colorCurvesEnabled === value) {
  41321. return;
  41322. }
  41323. this._colorCurvesEnabled = value;
  41324. this._updateParameters();
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41330. /**
  41331. * Gets wether the color grading effect is enabled.
  41332. */
  41333. get: function () {
  41334. return this._colorGradingEnabled;
  41335. },
  41336. /**
  41337. * Sets wether the color grading effect is enabled.
  41338. */
  41339. set: function (value) {
  41340. if (this._colorGradingEnabled === value) {
  41341. return;
  41342. }
  41343. this._colorGradingEnabled = value;
  41344. this._updateParameters();
  41345. },
  41346. enumerable: true,
  41347. configurable: true
  41348. });
  41349. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41350. /**
  41351. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41352. */
  41353. get: function () {
  41354. return this._colorGradingWithGreenDepth;
  41355. },
  41356. /**
  41357. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41358. */
  41359. set: function (value) {
  41360. if (this._colorGradingWithGreenDepth === value) {
  41361. return;
  41362. }
  41363. this._colorGradingWithGreenDepth = value;
  41364. this._updateParameters();
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41370. /**
  41371. * Gets wether the color grading texture contains BGR values.
  41372. */
  41373. get: function () {
  41374. return this._colorGradingBGR;
  41375. },
  41376. /**
  41377. * Sets wether the color grading texture contains BGR values.
  41378. */
  41379. set: function (value) {
  41380. if (this._colorGradingBGR === value) {
  41381. return;
  41382. }
  41383. this._colorGradingBGR = value;
  41384. this._updateParameters();
  41385. },
  41386. enumerable: true,
  41387. configurable: true
  41388. });
  41389. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41390. /**
  41391. * Gets the Exposure used in the effect.
  41392. */
  41393. get: function () {
  41394. return this._exposure;
  41395. },
  41396. /**
  41397. * Sets the Exposure used in the effect.
  41398. */
  41399. set: function (value) {
  41400. if (this._exposure === value) {
  41401. return;
  41402. }
  41403. this._exposure = value;
  41404. this._updateParameters();
  41405. },
  41406. enumerable: true,
  41407. configurable: true
  41408. });
  41409. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41410. /**
  41411. * Gets wether the tone mapping effect is enabled.
  41412. */
  41413. get: function () {
  41414. return this._toneMappingEnabled;
  41415. },
  41416. /**
  41417. * Sets wether the tone mapping effect is enabled.
  41418. */
  41419. set: function (value) {
  41420. if (this._toneMappingEnabled === value) {
  41421. return;
  41422. }
  41423. this._toneMappingEnabled = value;
  41424. this._updateParameters();
  41425. },
  41426. enumerable: true,
  41427. configurable: true
  41428. });
  41429. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41430. /**
  41431. * Gets the contrast used in the effect.
  41432. */
  41433. get: function () {
  41434. return this._contrast;
  41435. },
  41436. /**
  41437. * Sets the contrast used in the effect.
  41438. */
  41439. set: function (value) {
  41440. if (this._contrast === value) {
  41441. return;
  41442. }
  41443. this._contrast = value;
  41444. this._updateParameters();
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41450. /**
  41451. * Gets the vignette blend mode allowing different kind of effect.
  41452. */
  41453. get: function () {
  41454. return this._vignetteBlendMode;
  41455. },
  41456. /**
  41457. * Sets the vignette blend mode allowing different kind of effect.
  41458. */
  41459. set: function (value) {
  41460. if (this._vignetteBlendMode === value) {
  41461. return;
  41462. }
  41463. this._vignetteBlendMode = value;
  41464. this._updateParameters();
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41470. /**
  41471. * Gets wether the vignette effect is enabled.
  41472. */
  41473. get: function () {
  41474. return this._vignetteEnabled;
  41475. },
  41476. /**
  41477. * Sets wether the vignette effect is enabled.
  41478. */
  41479. set: function (value) {
  41480. if (this._vignetteEnabled === value) {
  41481. return;
  41482. }
  41483. this._vignetteEnabled = value;
  41484. this._updateParameters();
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41490. /**
  41491. * Gets wether the image processing is applied through a post process or not.
  41492. */
  41493. get: function () {
  41494. return this._applyByPostProcess;
  41495. },
  41496. /**
  41497. * Sets wether the image processing is applied through a post process or not.
  41498. */
  41499. set: function (value) {
  41500. if (this._applyByPostProcess === value) {
  41501. return;
  41502. }
  41503. this._applyByPostProcess = value;
  41504. this._updateParameters();
  41505. },
  41506. enumerable: true,
  41507. configurable: true
  41508. });
  41509. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41510. /**
  41511. * Gets wether the image processing is enabled or not.
  41512. */
  41513. get: function () {
  41514. return this._isEnabled;
  41515. },
  41516. /**
  41517. * Sets wether the image processing is enabled or not.
  41518. */
  41519. set: function (value) {
  41520. if (this._isEnabled === value) {
  41521. return;
  41522. }
  41523. this._isEnabled = value;
  41524. this._updateParameters();
  41525. },
  41526. enumerable: true,
  41527. configurable: true
  41528. });
  41529. /**
  41530. * Method called each time the image processing information changes requires to recompile the effect.
  41531. */
  41532. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41533. this.onUpdateParameters.notifyObservers(this);
  41534. };
  41535. ImageProcessingConfiguration.prototype.getClassName = function () {
  41536. return "ImageProcessingConfiguration";
  41537. };
  41538. /**
  41539. * Prepare the list of uniforms associated with the Image Processing effects.
  41540. * @param uniformsList The list of uniforms used in the effect
  41541. * @param defines the list of defines currently in use
  41542. */
  41543. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41544. if (defines.EXPOSURE) {
  41545. uniforms.push("exposureLinear");
  41546. }
  41547. if (defines.CONTRAST) {
  41548. uniforms.push("contrast");
  41549. }
  41550. if (defines.COLORGRADING) {
  41551. uniforms.push("colorTransformSettings");
  41552. }
  41553. if (defines.VIGNETTE) {
  41554. uniforms.push("vInverseScreenSize");
  41555. uniforms.push("vignetteSettings1");
  41556. uniforms.push("vignetteSettings2");
  41557. }
  41558. if (defines.COLORCURVES) {
  41559. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41560. }
  41561. };
  41562. /**
  41563. * Prepare the list of samplers associated with the Image Processing effects.
  41564. * @param uniformsList The list of uniforms used in the effect
  41565. * @param defines the list of defines currently in use
  41566. */
  41567. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41568. if (defines.COLORGRADING) {
  41569. samplersList.push("txColorTransform");
  41570. }
  41571. };
  41572. /**
  41573. * Prepare the list of defines associated to the shader.
  41574. * @param defines the list of defines to complete
  41575. */
  41576. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41577. if (forPostProcess === void 0) { forPostProcess = false; }
  41578. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41579. defines.VIGNETTE = false;
  41580. defines.TONEMAPPING = false;
  41581. defines.CONTRAST = false;
  41582. defines.EXPOSURE = false;
  41583. defines.COLORCURVES = false;
  41584. defines.COLORGRADING = false;
  41585. defines.COLORGRADING3D = false;
  41586. defines.IMAGEPROCESSING = false;
  41587. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41588. return;
  41589. }
  41590. defines.VIGNETTE = this.vignetteEnabled;
  41591. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41592. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41593. defines.TONEMAPPING = this.toneMappingEnabled;
  41594. defines.CONTRAST = (this.contrast !== 1.0);
  41595. defines.EXPOSURE = (this.exposure !== 1.0);
  41596. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41597. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41598. if (defines.COLORGRADING) {
  41599. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41600. }
  41601. else {
  41602. defines.COLORGRADING3D = false;
  41603. }
  41604. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41605. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41606. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41607. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41608. };
  41609. /**
  41610. * Returns true if all the image processing information are ready.
  41611. */
  41612. ImageProcessingConfiguration.prototype.isReady = function () {
  41613. // Color Grading texure can not be none blocking.
  41614. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41615. };
  41616. /**
  41617. * Binds the image processing to the shader.
  41618. * @param effect The effect to bind to
  41619. */
  41620. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41621. if (aspectRatio === void 0) { aspectRatio = 1; }
  41622. // Color Curves
  41623. if (this._colorCurvesEnabled && this.colorCurves) {
  41624. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41625. }
  41626. // Vignette
  41627. if (this._vignetteEnabled) {
  41628. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41629. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41630. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41631. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41632. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41633. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41634. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41635. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41636. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41637. var vignettePower = -2.0 * this.vignetteWeight;
  41638. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41639. }
  41640. // Exposure
  41641. effect.setFloat("exposureLinear", this.exposure);
  41642. // Contrast
  41643. effect.setFloat("contrast", this.contrast);
  41644. // Color transform settings
  41645. if (this.colorGradingTexture) {
  41646. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41647. var textureSize = this.colorGradingTexture.getSize().height;
  41648. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41649. 0.5 / textureSize, // textureOffset
  41650. textureSize, // textureSize
  41651. this.colorGradingTexture.level // weight
  41652. );
  41653. }
  41654. };
  41655. /**
  41656. * Clones the current image processing instance.
  41657. * @return The cloned image processing
  41658. */
  41659. ImageProcessingConfiguration.prototype.clone = function () {
  41660. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41661. };
  41662. /**
  41663. * Serializes the current image processing instance to a json representation.
  41664. * @return a JSON representation
  41665. */
  41666. ImageProcessingConfiguration.prototype.serialize = function () {
  41667. return BABYLON.SerializationHelper.Serialize(this);
  41668. };
  41669. /**
  41670. * Parses the image processing from a json representation.
  41671. * @param source the JSON source to parse
  41672. * @return The parsed image processing
  41673. */
  41674. ImageProcessingConfiguration.Parse = function (source) {
  41675. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41676. };
  41677. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41678. /**
  41679. * Used to apply the vignette as a mix with the pixel color.
  41680. */
  41681. get: function () {
  41682. return this._VIGNETTEMODE_MULTIPLY;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41688. /**
  41689. * Used to apply the vignette as a replacement of the pixel color.
  41690. */
  41691. get: function () {
  41692. return this._VIGNETTEMODE_OPAQUE;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. // Static constants associated to the image processing.
  41698. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41699. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41700. __decorate([
  41701. BABYLON.serializeAsColorCurves()
  41702. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41703. __decorate([
  41704. BABYLON.serialize()
  41705. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41706. __decorate([
  41707. BABYLON.serializeAsTexture()
  41708. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41709. __decorate([
  41710. BABYLON.serialize()
  41711. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41712. __decorate([
  41713. BABYLON.serialize()
  41714. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41715. __decorate([
  41716. BABYLON.serialize()
  41717. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41718. __decorate([
  41719. BABYLON.serialize()
  41720. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41721. __decorate([
  41722. BABYLON.serialize()
  41723. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41724. __decorate([
  41725. BABYLON.serialize()
  41726. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41727. __decorate([
  41728. BABYLON.serialize()
  41729. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41730. __decorate([
  41731. BABYLON.serialize()
  41732. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41733. __decorate([
  41734. BABYLON.serialize()
  41735. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41739. __decorate([
  41740. BABYLON.serializeAsColor4()
  41741. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41745. __decorate([
  41746. BABYLON.serialize()
  41747. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41748. __decorate([
  41749. BABYLON.serialize()
  41750. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41757. return ImageProcessingConfiguration;
  41758. }());
  41759. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41760. })(BABYLON || (BABYLON = {}));
  41761. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41762. var BABYLON;
  41763. (function (BABYLON) {
  41764. /**
  41765. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41766. * It can help converting any input color in a desired output one. This can then be used to create effects
  41767. * from sepia, black and white to sixties or futuristic rendering...
  41768. *
  41769. * The only supported format is currently 3dl.
  41770. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41771. */
  41772. var ColorGradingTexture = /** @class */ (function (_super) {
  41773. __extends(ColorGradingTexture, _super);
  41774. /**
  41775. * Instantiates a ColorGradingTexture from the following parameters.
  41776. *
  41777. * @param url The location of the color gradind data (currently only supporting 3dl)
  41778. * @param scene The scene the texture will be used in
  41779. */
  41780. function ColorGradingTexture(url, scene) {
  41781. var _this = _super.call(this, scene) || this;
  41782. if (!url) {
  41783. return _this;
  41784. }
  41785. _this._engine = scene.getEngine();
  41786. _this._textureMatrix = BABYLON.Matrix.Identity();
  41787. _this.name = url;
  41788. _this.url = url;
  41789. _this.hasAlpha = false;
  41790. _this.isCube = false;
  41791. _this.is3D = _this._engine.webGLVersion > 1;
  41792. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41793. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41794. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41795. _this.anisotropicFilteringLevel = 1;
  41796. _this._texture = _this._getFromCache(url, true);
  41797. if (!_this._texture) {
  41798. if (!scene.useDelayedTextureLoading) {
  41799. _this.loadTexture();
  41800. }
  41801. else {
  41802. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41803. }
  41804. }
  41805. return _this;
  41806. }
  41807. /**
  41808. * Returns the texture matrix used in most of the material.
  41809. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41810. */
  41811. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41812. return this._textureMatrix;
  41813. };
  41814. /**
  41815. * Occurs when the file being loaded is a .3dl LUT file.
  41816. */
  41817. ColorGradingTexture.prototype.load3dlTexture = function () {
  41818. var engine = this._engine;
  41819. var texture;
  41820. if (engine.webGLVersion === 1) {
  41821. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41822. }
  41823. else {
  41824. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41825. }
  41826. this._texture = texture;
  41827. var callback = function (text) {
  41828. if (typeof text !== "string") {
  41829. return;
  41830. }
  41831. var data = null;
  41832. var tempData = null;
  41833. var line;
  41834. var lines = text.split('\n');
  41835. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41836. var maxColor = 0;
  41837. for (var i = 0; i < lines.length; i++) {
  41838. line = lines[i];
  41839. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41840. continue;
  41841. if (line.indexOf('#') === 0)
  41842. continue;
  41843. var words = line.split(" ");
  41844. if (size === 0) {
  41845. // Number of space + one
  41846. size = words.length;
  41847. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41848. tempData = new Float32Array(size * size * size * 4);
  41849. continue;
  41850. }
  41851. if (size != 0) {
  41852. var r = Math.max(parseInt(words[0]), 0);
  41853. var g = Math.max(parseInt(words[1]), 0);
  41854. var b = Math.max(parseInt(words[2]), 0);
  41855. maxColor = Math.max(r, maxColor);
  41856. maxColor = Math.max(g, maxColor);
  41857. maxColor = Math.max(b, maxColor);
  41858. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41859. if (tempData) {
  41860. tempData[pixelStorageIndex + 0] = r;
  41861. tempData[pixelStorageIndex + 1] = g;
  41862. tempData[pixelStorageIndex + 2] = b;
  41863. }
  41864. pixelIndexSlice++;
  41865. if (pixelIndexSlice % size == 0) {
  41866. pixelIndexH++;
  41867. pixelIndexSlice = 0;
  41868. if (pixelIndexH % size == 0) {
  41869. pixelIndexW++;
  41870. pixelIndexH = 0;
  41871. }
  41872. }
  41873. }
  41874. }
  41875. if (tempData && data) {
  41876. for (var i = 0; i < tempData.length; i++) {
  41877. if (i > 0 && (i + 1) % 4 === 0) {
  41878. data[i] = 255;
  41879. }
  41880. else {
  41881. var value = tempData[i];
  41882. data[i] = (value / maxColor * 255);
  41883. }
  41884. }
  41885. }
  41886. if (texture.is3D) {
  41887. texture.updateSize(size, size, size);
  41888. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41889. }
  41890. else {
  41891. texture.updateSize(size * size, size);
  41892. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41893. }
  41894. };
  41895. var scene = this.getScene();
  41896. if (scene) {
  41897. scene._loadFile(this.url, callback);
  41898. }
  41899. else {
  41900. this._engine._loadFile(this.url, callback);
  41901. }
  41902. return this._texture;
  41903. };
  41904. /**
  41905. * Starts the loading process of the texture.
  41906. */
  41907. ColorGradingTexture.prototype.loadTexture = function () {
  41908. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41909. this.load3dlTexture();
  41910. }
  41911. };
  41912. /**
  41913. * Clones the color gradind texture.
  41914. */
  41915. ColorGradingTexture.prototype.clone = function () {
  41916. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41917. // Base texture
  41918. newTexture.level = this.level;
  41919. return newTexture;
  41920. };
  41921. /**
  41922. * Called during delayed load for textures.
  41923. */
  41924. ColorGradingTexture.prototype.delayLoad = function () {
  41925. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41926. return;
  41927. }
  41928. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41929. this._texture = this._getFromCache(this.url, true);
  41930. if (!this._texture) {
  41931. this.loadTexture();
  41932. }
  41933. };
  41934. /**
  41935. * Parses a color grading texture serialized by Babylon.
  41936. * @param parsedTexture The texture information being parsedTexture
  41937. * @param scene The scene to load the texture in
  41938. * @param rootUrl The root url of the data assets to load
  41939. * @return A color gradind texture
  41940. */
  41941. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41942. var texture = null;
  41943. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41944. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41945. texture.name = parsedTexture.name;
  41946. texture.level = parsedTexture.level;
  41947. }
  41948. return texture;
  41949. };
  41950. /**
  41951. * Serializes the LUT texture to json format.
  41952. */
  41953. ColorGradingTexture.prototype.serialize = function () {
  41954. if (!this.name) {
  41955. return null;
  41956. }
  41957. var serializationObject = {};
  41958. serializationObject.name = this.name;
  41959. serializationObject.level = this.level;
  41960. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41961. return serializationObject;
  41962. };
  41963. /**
  41964. * Empty line regex stored for GC.
  41965. */
  41966. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41967. return ColorGradingTexture;
  41968. }(BABYLON.BaseTexture));
  41969. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41970. })(BABYLON || (BABYLON = {}));
  41971. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41972. var BABYLON;
  41973. (function (BABYLON) {
  41974. /**
  41975. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41976. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41977. * 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;
  41978. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41979. */
  41980. var ColorCurves = /** @class */ (function () {
  41981. function ColorCurves() {
  41982. this._dirty = true;
  41983. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41984. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41985. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41986. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41987. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41988. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41989. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41990. this._globalHue = 30;
  41991. this._globalDensity = 0;
  41992. this._globalSaturation = 0;
  41993. this._globalExposure = 0;
  41994. this._highlightsHue = 30;
  41995. this._highlightsDensity = 0;
  41996. this._highlightsSaturation = 0;
  41997. this._highlightsExposure = 0;
  41998. this._midtonesHue = 30;
  41999. this._midtonesDensity = 0;
  42000. this._midtonesSaturation = 0;
  42001. this._midtonesExposure = 0;
  42002. this._shadowsHue = 30;
  42003. this._shadowsDensity = 0;
  42004. this._shadowsSaturation = 0;
  42005. this._shadowsExposure = 0;
  42006. }
  42007. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  42008. /**
  42009. * Gets the global Hue value.
  42010. * 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).
  42011. */
  42012. get: function () {
  42013. return this._globalHue;
  42014. },
  42015. /**
  42016. * Sets the global Hue value.
  42017. * 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).
  42018. */
  42019. set: function (value) {
  42020. this._globalHue = value;
  42021. this._dirty = true;
  42022. },
  42023. enumerable: true,
  42024. configurable: true
  42025. });
  42026. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42027. /**
  42028. * Gets the global Density value.
  42029. * 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.
  42030. * Values less than zero provide a filter of opposite hue.
  42031. */
  42032. get: function () {
  42033. return this._globalDensity;
  42034. },
  42035. /**
  42036. * Sets the global Density value.
  42037. * 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.
  42038. * Values less than zero provide a filter of opposite hue.
  42039. */
  42040. set: function (value) {
  42041. this._globalDensity = value;
  42042. this._dirty = true;
  42043. },
  42044. enumerable: true,
  42045. configurable: true
  42046. });
  42047. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42048. /**
  42049. * Gets the global Saturation value.
  42050. * 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.
  42051. */
  42052. get: function () {
  42053. return this._globalSaturation;
  42054. },
  42055. /**
  42056. * Sets the global Saturation value.
  42057. * 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.
  42058. */
  42059. set: function (value) {
  42060. this._globalSaturation = value;
  42061. this._dirty = true;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42067. /**
  42068. * Gets the global Exposure value.
  42069. * 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.
  42070. */
  42071. get: function () {
  42072. return this._globalExposure;
  42073. },
  42074. /**
  42075. * Sets the global Exposure value.
  42076. * 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.
  42077. */
  42078. set: function (value) {
  42079. this._globalExposure = value;
  42080. this._dirty = true;
  42081. },
  42082. enumerable: true,
  42083. configurable: true
  42084. });
  42085. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42086. /**
  42087. * Gets the highlights Hue value.
  42088. * 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).
  42089. */
  42090. get: function () {
  42091. return this._highlightsHue;
  42092. },
  42093. /**
  42094. * Sets the highlights Hue value.
  42095. * 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).
  42096. */
  42097. set: function (value) {
  42098. this._highlightsHue = value;
  42099. this._dirty = true;
  42100. },
  42101. enumerable: true,
  42102. configurable: true
  42103. });
  42104. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42105. /**
  42106. * Gets the highlights Density value.
  42107. * 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.
  42108. * Values less than zero provide a filter of opposite hue.
  42109. */
  42110. get: function () {
  42111. return this._highlightsDensity;
  42112. },
  42113. /**
  42114. * Sets the highlights Density value.
  42115. * 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.
  42116. * Values less than zero provide a filter of opposite hue.
  42117. */
  42118. set: function (value) {
  42119. this._highlightsDensity = value;
  42120. this._dirty = true;
  42121. },
  42122. enumerable: true,
  42123. configurable: true
  42124. });
  42125. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42126. /**
  42127. * Gets the highlights Saturation value.
  42128. * 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.
  42129. */
  42130. get: function () {
  42131. return this._highlightsSaturation;
  42132. },
  42133. /**
  42134. * Sets the highlights Saturation value.
  42135. * 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.
  42136. */
  42137. set: function (value) {
  42138. this._highlightsSaturation = value;
  42139. this._dirty = true;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42145. /**
  42146. * Gets the highlights Exposure value.
  42147. * 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.
  42148. */
  42149. get: function () {
  42150. return this._highlightsExposure;
  42151. },
  42152. /**
  42153. * Sets the highlights Exposure value.
  42154. * 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.
  42155. */
  42156. set: function (value) {
  42157. this._highlightsExposure = value;
  42158. this._dirty = true;
  42159. },
  42160. enumerable: true,
  42161. configurable: true
  42162. });
  42163. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42164. /**
  42165. * Gets the midtones Hue value.
  42166. * 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).
  42167. */
  42168. get: function () {
  42169. return this._midtonesHue;
  42170. },
  42171. /**
  42172. * Sets the midtones Hue value.
  42173. * 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).
  42174. */
  42175. set: function (value) {
  42176. this._midtonesHue = value;
  42177. this._dirty = true;
  42178. },
  42179. enumerable: true,
  42180. configurable: true
  42181. });
  42182. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42183. /**
  42184. * Gets the midtones Density value.
  42185. * 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.
  42186. * Values less than zero provide a filter of opposite hue.
  42187. */
  42188. get: function () {
  42189. return this._midtonesDensity;
  42190. },
  42191. /**
  42192. * Sets the midtones Density value.
  42193. * 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.
  42194. * Values less than zero provide a filter of opposite hue.
  42195. */
  42196. set: function (value) {
  42197. this._midtonesDensity = value;
  42198. this._dirty = true;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42204. /**
  42205. * Gets the midtones Saturation value.
  42206. * 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.
  42207. */
  42208. get: function () {
  42209. return this._midtonesSaturation;
  42210. },
  42211. /**
  42212. * Sets the midtones Saturation value.
  42213. * 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.
  42214. */
  42215. set: function (value) {
  42216. this._midtonesSaturation = value;
  42217. this._dirty = true;
  42218. },
  42219. enumerable: true,
  42220. configurable: true
  42221. });
  42222. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42223. /**
  42224. * Gets the midtones Exposure value.
  42225. * 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.
  42226. */
  42227. get: function () {
  42228. return this._midtonesExposure;
  42229. },
  42230. /**
  42231. * Sets the midtones Exposure value.
  42232. * 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.
  42233. */
  42234. set: function (value) {
  42235. this._midtonesExposure = value;
  42236. this._dirty = true;
  42237. },
  42238. enumerable: true,
  42239. configurable: true
  42240. });
  42241. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42242. /**
  42243. * Gets the shadows Hue value.
  42244. * 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).
  42245. */
  42246. get: function () {
  42247. return this._shadowsHue;
  42248. },
  42249. /**
  42250. * Sets the shadows Hue value.
  42251. * 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).
  42252. */
  42253. set: function (value) {
  42254. this._shadowsHue = value;
  42255. this._dirty = true;
  42256. },
  42257. enumerable: true,
  42258. configurable: true
  42259. });
  42260. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42261. /**
  42262. * Gets the shadows Density value.
  42263. * 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.
  42264. * Values less than zero provide a filter of opposite hue.
  42265. */
  42266. get: function () {
  42267. return this._shadowsDensity;
  42268. },
  42269. /**
  42270. * Sets the shadows Density value.
  42271. * 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.
  42272. * Values less than zero provide a filter of opposite hue.
  42273. */
  42274. set: function (value) {
  42275. this._shadowsDensity = value;
  42276. this._dirty = true;
  42277. },
  42278. enumerable: true,
  42279. configurable: true
  42280. });
  42281. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42282. /**
  42283. * Gets the shadows Saturation value.
  42284. * 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.
  42285. */
  42286. get: function () {
  42287. return this._shadowsSaturation;
  42288. },
  42289. /**
  42290. * Sets the shadows Saturation value.
  42291. * 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.
  42292. */
  42293. set: function (value) {
  42294. this._shadowsSaturation = value;
  42295. this._dirty = true;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42301. /**
  42302. * Gets the shadows Exposure value.
  42303. * 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.
  42304. */
  42305. get: function () {
  42306. return this._shadowsExposure;
  42307. },
  42308. /**
  42309. * Sets the shadows Exposure value.
  42310. * 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.
  42311. */
  42312. set: function (value) {
  42313. this._shadowsExposure = value;
  42314. this._dirty = true;
  42315. },
  42316. enumerable: true,
  42317. configurable: true
  42318. });
  42319. ColorCurves.prototype.getClassName = function () {
  42320. return "ColorCurves";
  42321. };
  42322. /**
  42323. * Binds the color curves to the shader.
  42324. * @param colorCurves The color curve to bind
  42325. * @param effect The effect to bind to
  42326. */
  42327. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42328. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42329. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42330. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42331. if (colorCurves._dirty) {
  42332. colorCurves._dirty = false;
  42333. // Fill in global info.
  42334. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42335. // Compute highlights info.
  42336. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42337. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42338. // Compute midtones info.
  42339. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42340. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42341. // Compute shadows info.
  42342. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42343. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42344. // Compute deltas (neutral is midtones).
  42345. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42346. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42347. }
  42348. if (effect) {
  42349. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42350. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42351. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42352. }
  42353. };
  42354. /**
  42355. * Prepare the list of uniforms associated with the ColorCurves effects.
  42356. * @param uniformsList The list of uniforms used in the effect
  42357. */
  42358. ColorCurves.PrepareUniforms = function (uniformsList) {
  42359. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42360. };
  42361. /**
  42362. * Returns color grading data based on a hue, density, saturation and exposure value.
  42363. * @param filterHue The hue of the color filter.
  42364. * @param filterDensity The density of the color filter.
  42365. * @param saturation The saturation.
  42366. * @param exposure The exposure.
  42367. * @param result The result data container.
  42368. */
  42369. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42370. if (hue == null) {
  42371. return;
  42372. }
  42373. hue = ColorCurves.clamp(hue, 0, 360);
  42374. density = ColorCurves.clamp(density, -100, 100);
  42375. saturation = ColorCurves.clamp(saturation, -100, 100);
  42376. exposure = ColorCurves.clamp(exposure, -100, 100);
  42377. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42378. // so that the maximum filter density is only 50% control. This provides fine control
  42379. // for small values and reasonable range.
  42380. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42381. density *= 0.5;
  42382. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42383. if (density < 0) {
  42384. density *= -1;
  42385. hue = (hue + 180) % 360;
  42386. }
  42387. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42388. result.scaleToRef(2, result);
  42389. result.a = 1 + 0.01 * saturation;
  42390. };
  42391. /**
  42392. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42393. * @param value The input slider value in range [-100,100].
  42394. * @returns Adjusted value.
  42395. */
  42396. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42397. value /= 100;
  42398. var x = Math.abs(value);
  42399. x = Math.pow(x, 2);
  42400. if (value < 0) {
  42401. x *= -1;
  42402. }
  42403. x *= 100;
  42404. return x;
  42405. };
  42406. /**
  42407. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42408. * @param hue The hue (H) input.
  42409. * @param saturation The saturation (S) input.
  42410. * @param brightness The brightness (B) input.
  42411. * @result An RGBA color represented as Vector4.
  42412. */
  42413. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42414. var h = ColorCurves.clamp(hue, 0, 360);
  42415. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42416. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42417. if (s === 0) {
  42418. result.r = v;
  42419. result.g = v;
  42420. result.b = v;
  42421. }
  42422. else {
  42423. // sector 0 to 5
  42424. h /= 60;
  42425. var i = Math.floor(h);
  42426. // fractional part of h
  42427. var f = h - i;
  42428. var p = v * (1 - s);
  42429. var q = v * (1 - s * f);
  42430. var t = v * (1 - s * (1 - f));
  42431. switch (i) {
  42432. case 0:
  42433. result.r = v;
  42434. result.g = t;
  42435. result.b = p;
  42436. break;
  42437. case 1:
  42438. result.r = q;
  42439. result.g = v;
  42440. result.b = p;
  42441. break;
  42442. case 2:
  42443. result.r = p;
  42444. result.g = v;
  42445. result.b = t;
  42446. break;
  42447. case 3:
  42448. result.r = p;
  42449. result.g = q;
  42450. result.b = v;
  42451. break;
  42452. case 4:
  42453. result.r = t;
  42454. result.g = p;
  42455. result.b = v;
  42456. break;
  42457. default: // case 5:
  42458. result.r = v;
  42459. result.g = p;
  42460. result.b = q;
  42461. break;
  42462. }
  42463. }
  42464. result.a = 1;
  42465. };
  42466. /**
  42467. * Returns a value clamped between min and max
  42468. * @param value The value to clamp
  42469. * @param min The minimum of value
  42470. * @param max The maximum of value
  42471. * @returns The clamped value.
  42472. */
  42473. ColorCurves.clamp = function (value, min, max) {
  42474. return Math.min(Math.max(value, min), max);
  42475. };
  42476. /**
  42477. * Clones the current color curve instance.
  42478. * @return The cloned curves
  42479. */
  42480. ColorCurves.prototype.clone = function () {
  42481. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42482. };
  42483. /**
  42484. * Serializes the current color curve instance to a json representation.
  42485. * @return a JSON representation
  42486. */
  42487. ColorCurves.prototype.serialize = function () {
  42488. return BABYLON.SerializationHelper.Serialize(this);
  42489. };
  42490. /**
  42491. * Parses the color curve from a json representation.
  42492. * @param source the JSON source to parse
  42493. * @return The parsed curves
  42494. */
  42495. ColorCurves.Parse = function (source) {
  42496. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42497. };
  42498. __decorate([
  42499. BABYLON.serialize()
  42500. ], ColorCurves.prototype, "_globalHue", void 0);
  42501. __decorate([
  42502. BABYLON.serialize()
  42503. ], ColorCurves.prototype, "_globalDensity", void 0);
  42504. __decorate([
  42505. BABYLON.serialize()
  42506. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42507. __decorate([
  42508. BABYLON.serialize()
  42509. ], ColorCurves.prototype, "_globalExposure", void 0);
  42510. __decorate([
  42511. BABYLON.serialize()
  42512. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42522. __decorate([
  42523. BABYLON.serialize()
  42524. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42528. __decorate([
  42529. BABYLON.serialize()
  42530. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42531. __decorate([
  42532. BABYLON.serialize()
  42533. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42534. return ColorCurves;
  42535. }());
  42536. BABYLON.ColorCurves = ColorCurves;
  42537. })(BABYLON || (BABYLON = {}));
  42538. //# sourceMappingURL=babylon.colorCurves.js.map
  42539. //# sourceMappingURL=babylon.behavior.js.map
  42540. var BABYLON;
  42541. (function (BABYLON) {
  42542. /**
  42543. * "Static Class" containing the most commonly used helper while dealing with material for
  42544. * rendering purpose.
  42545. *
  42546. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42547. *
  42548. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42549. */
  42550. var MaterialHelper = /** @class */ (function () {
  42551. function MaterialHelper() {
  42552. }
  42553. /**
  42554. * Bind the current view position to an effect.
  42555. * @param effect The effect to be bound
  42556. * @param scene The scene the eyes position is used from
  42557. */
  42558. MaterialHelper.BindEyePosition = function (effect, scene) {
  42559. if (scene._forcedViewPosition) {
  42560. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42561. return;
  42562. }
  42563. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42564. };
  42565. /**
  42566. * Helps preparing the defines values about the UVs in used in the effect.
  42567. * UVs are shared as much as we can accross chanels in the shaders.
  42568. * @param texture The texture we are preparing the UVs for
  42569. * @param defines The defines to update
  42570. * @param key The chanel key "diffuse", "specular"... used in the shader
  42571. */
  42572. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42573. defines._needUVs = true;
  42574. defines[key] = true;
  42575. if (texture.getTextureMatrix().isIdentity(true)) {
  42576. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42577. if (texture.coordinatesIndex === 0) {
  42578. defines["MAINUV1"] = true;
  42579. }
  42580. else {
  42581. defines["MAINUV2"] = true;
  42582. }
  42583. }
  42584. else {
  42585. defines[key + "DIRECTUV"] = 0;
  42586. }
  42587. };
  42588. /**
  42589. * Binds a texture matrix value to its corrsponding uniform
  42590. * @param texture The texture to bind the matrix for
  42591. * @param uniformBuffer The uniform buffer receivin the data
  42592. * @param key The chanel key "diffuse", "specular"... used in the shader
  42593. */
  42594. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42595. var matrix = texture.getTextureMatrix();
  42596. if (!matrix.isIdentity(true)) {
  42597. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42598. }
  42599. };
  42600. /**
  42601. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42602. * @param mesh defines the current mesh
  42603. * @param scene defines the current scene
  42604. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42605. * @param pointsCloud defines if point cloud rendering has to be turned on
  42606. * @param fogEnabled defines if fog has to be turned on
  42607. * @param alphaTest defines if alpha testing has to be turned on
  42608. * @param defines defines the current list of defines
  42609. */
  42610. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42611. if (defines._areMiscDirty) {
  42612. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42613. defines["POINTSIZE"] = pointsCloud;
  42614. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42615. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42616. defines["ALPHATEST"] = alphaTest;
  42617. }
  42618. };
  42619. /**
  42620. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42621. * @param scene defines the current scene
  42622. * @param engine defines the current engine
  42623. * @param defines specifies the list of active defines
  42624. * @param useInstances defines if instances have to be turned on
  42625. * @param useClipPlane defines if clip plane have to be turned on
  42626. */
  42627. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42628. if (useClipPlane === void 0) { useClipPlane = null; }
  42629. var changed = false;
  42630. if (useClipPlane == null) {
  42631. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42632. }
  42633. if (defines["CLIPPLANE"] !== useClipPlane) {
  42634. defines["CLIPPLANE"] = useClipPlane;
  42635. changed = true;
  42636. }
  42637. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42638. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42639. changed = true;
  42640. }
  42641. if (defines["INSTANCES"] !== useInstances) {
  42642. defines["INSTANCES"] = useInstances;
  42643. changed = true;
  42644. }
  42645. if (changed) {
  42646. defines.markAsUnprocessed();
  42647. }
  42648. };
  42649. /**
  42650. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42651. * @param mesh The mesh containing the geometry data we will draw
  42652. * @param defines The defines to update
  42653. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42654. * @param useBones Precise whether bones should be used or not (override mesh info)
  42655. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42656. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42657. * @returns false if defines are considered not dirty and have not been checked
  42658. */
  42659. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42660. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42661. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42662. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42663. return false;
  42664. }
  42665. defines._normals = defines._needNormals;
  42666. defines._uvs = defines._needUVs;
  42667. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42668. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42669. defines["TANGENT"] = true;
  42670. }
  42671. if (defines._needUVs) {
  42672. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42673. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42674. }
  42675. else {
  42676. defines["UV1"] = false;
  42677. defines["UV2"] = false;
  42678. }
  42679. if (useVertexColor) {
  42680. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42681. defines["VERTEXCOLOR"] = hasVertexColors;
  42682. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42683. }
  42684. if (useBones) {
  42685. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42686. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42687. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42688. }
  42689. else {
  42690. defines["NUM_BONE_INFLUENCERS"] = 0;
  42691. defines["BonesPerMesh"] = 0;
  42692. }
  42693. }
  42694. if (useMorphTargets) {
  42695. var manager = mesh.morphTargetManager;
  42696. if (manager) {
  42697. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42698. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42699. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42700. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42701. }
  42702. else {
  42703. defines["MORPHTARGETS_TANGENT"] = false;
  42704. defines["MORPHTARGETS_NORMAL"] = false;
  42705. defines["MORPHTARGETS"] = false;
  42706. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42707. }
  42708. }
  42709. return true;
  42710. };
  42711. /**
  42712. * Prepares the defines related to the light information passed in parameter
  42713. * @param scene The scene we are intending to draw
  42714. * @param mesh The mesh the effect is compiling for
  42715. * @param defines The defines to update
  42716. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42717. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42718. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42719. * @returns true if normals will be required for the rest of the effect
  42720. */
  42721. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42722. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42723. if (disableLighting === void 0) { disableLighting = false; }
  42724. if (!defines._areLightsDirty) {
  42725. return defines._needNormals;
  42726. }
  42727. var lightIndex = 0;
  42728. var needNormals = false;
  42729. var needRebuild = false;
  42730. var lightmapMode = false;
  42731. var shadowEnabled = false;
  42732. var specularEnabled = false;
  42733. if (scene.lightsEnabled && !disableLighting) {
  42734. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42735. var light = _a[_i];
  42736. needNormals = true;
  42737. if (defines["LIGHT" + lightIndex] === undefined) {
  42738. needRebuild = true;
  42739. }
  42740. defines["LIGHT" + lightIndex] = true;
  42741. defines["SPOTLIGHT" + lightIndex] = false;
  42742. defines["HEMILIGHT" + lightIndex] = false;
  42743. defines["POINTLIGHT" + lightIndex] = false;
  42744. defines["DIRLIGHT" + lightIndex] = false;
  42745. var type;
  42746. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42747. type = "SPOTLIGHT" + lightIndex;
  42748. var spotLight = light;
  42749. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42750. }
  42751. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42752. type = "HEMILIGHT" + lightIndex;
  42753. }
  42754. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42755. type = "POINTLIGHT" + lightIndex;
  42756. }
  42757. else {
  42758. type = "DIRLIGHT" + lightIndex;
  42759. }
  42760. defines[type] = true;
  42761. // Specular
  42762. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42763. specularEnabled = true;
  42764. }
  42765. // Shadows
  42766. defines["SHADOW" + lightIndex] = false;
  42767. defines["SHADOWPCF" + lightIndex] = false;
  42768. defines["SHADOWPCSS" + lightIndex] = false;
  42769. defines["SHADOWPOISSON" + lightIndex] = false;
  42770. defines["SHADOWESM" + lightIndex] = false;
  42771. defines["SHADOWCUBE" + lightIndex] = false;
  42772. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42773. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42774. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42775. var shadowGenerator = light.getShadowGenerator();
  42776. if (shadowGenerator) {
  42777. shadowEnabled = true;
  42778. shadowGenerator.prepareDefines(defines, lightIndex);
  42779. }
  42780. }
  42781. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42782. lightmapMode = true;
  42783. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42784. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42785. }
  42786. else {
  42787. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42788. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42789. }
  42790. lightIndex++;
  42791. if (lightIndex === maxSimultaneousLights)
  42792. break;
  42793. }
  42794. }
  42795. defines["SPECULARTERM"] = specularEnabled;
  42796. defines["SHADOWS"] = shadowEnabled;
  42797. // Resetting all other lights if any
  42798. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42799. if (defines["LIGHT" + index] !== undefined) {
  42800. defines["LIGHT" + index] = false;
  42801. defines["HEMILIGHT" + lightIndex] = false;
  42802. defines["POINTLIGHT" + lightIndex] = false;
  42803. defines["DIRLIGHT" + lightIndex] = false;
  42804. defines["SPOTLIGHT" + lightIndex] = false;
  42805. defines["SHADOW" + lightIndex] = false;
  42806. }
  42807. }
  42808. var caps = scene.getEngine().getCaps();
  42809. if (defines["SHADOWFLOAT"] === undefined) {
  42810. needRebuild = true;
  42811. }
  42812. defines["SHADOWFLOAT"] = shadowEnabled &&
  42813. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42814. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42815. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42816. if (needRebuild) {
  42817. defines.rebuild();
  42818. }
  42819. return needNormals;
  42820. };
  42821. /**
  42822. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42823. * that won t be acctive due to defines being turned off.
  42824. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42825. * @param samplersList The samplers list
  42826. * @param defines The defines helping in the list generation
  42827. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42828. */
  42829. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42830. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42831. var uniformsList;
  42832. var uniformBuffersList = null;
  42833. if (uniformsListOrOptions.uniformsNames) {
  42834. var options = uniformsListOrOptions;
  42835. uniformsList = options.uniformsNames;
  42836. uniformBuffersList = options.uniformBuffersNames;
  42837. samplersList = options.samplers;
  42838. defines = options.defines;
  42839. maxSimultaneousLights = options.maxSimultaneousLights;
  42840. }
  42841. else {
  42842. uniformsList = uniformsListOrOptions;
  42843. if (!samplersList) {
  42844. samplersList = [];
  42845. }
  42846. }
  42847. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42848. if (!defines["LIGHT" + lightIndex]) {
  42849. break;
  42850. }
  42851. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42852. if (uniformBuffersList) {
  42853. uniformBuffersList.push("Light" + lightIndex);
  42854. }
  42855. samplersList.push("shadowSampler" + lightIndex);
  42856. samplersList.push("depthSampler" + lightIndex);
  42857. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42858. samplersList.push("projectionLightSampler" + lightIndex);
  42859. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42860. }
  42861. }
  42862. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42863. uniformsList.push("morphTargetInfluences");
  42864. }
  42865. };
  42866. /**
  42867. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42868. * @param defines The defines to update while falling back
  42869. * @param fallbacks The authorized effect fallbacks
  42870. * @param maxSimultaneousLights The maximum number of lights allowed
  42871. * @param rank the current rank of the Effect
  42872. * @returns The newly affected rank
  42873. */
  42874. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42875. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42876. if (rank === void 0) { rank = 0; }
  42877. var lightFallbackRank = 0;
  42878. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42879. if (!defines["LIGHT" + lightIndex]) {
  42880. break;
  42881. }
  42882. if (lightIndex > 0) {
  42883. lightFallbackRank = rank + lightIndex;
  42884. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42885. }
  42886. if (!defines["SHADOWS"]) {
  42887. if (defines["SHADOW" + lightIndex]) {
  42888. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42889. }
  42890. if (defines["SHADOWPCF" + lightIndex]) {
  42891. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42892. }
  42893. if (defines["SHADOWPCSS" + lightIndex]) {
  42894. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42895. }
  42896. if (defines["SHADOWPOISSON" + lightIndex]) {
  42897. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42898. }
  42899. if (defines["SHADOWESM" + lightIndex]) {
  42900. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42901. }
  42902. }
  42903. }
  42904. return lightFallbackRank++;
  42905. };
  42906. /**
  42907. * Prepares the list of attributes required for morph targets according to the effect defines.
  42908. * @param attribs The current list of supported attribs
  42909. * @param mesh The mesh to prepare the morph targets attributes for
  42910. * @param defines The current Defines of the effect
  42911. */
  42912. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42913. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42914. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42915. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42916. var manager = mesh.morphTargetManager;
  42917. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42918. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42919. for (var index = 0; index < influencers; index++) {
  42920. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42921. if (normal) {
  42922. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42923. }
  42924. if (tangent) {
  42925. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42926. }
  42927. if (attribs.length > maxAttributesCount) {
  42928. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42929. }
  42930. }
  42931. }
  42932. };
  42933. /**
  42934. * Prepares the list of attributes required for bones according to the effect defines.
  42935. * @param attribs The current list of supported attribs
  42936. * @param mesh The mesh to prepare the bones attributes for
  42937. * @param defines The current Defines of the effect
  42938. * @param fallbacks The current efffect fallback strategy
  42939. */
  42940. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42941. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42942. fallbacks.addCPUSkinningFallback(0, mesh);
  42943. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42944. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42945. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42946. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42947. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42948. }
  42949. }
  42950. };
  42951. /**
  42952. * Prepares the list of attributes required for instances according to the effect defines.
  42953. * @param attribs The current list of supported attribs
  42954. * @param defines The current Defines of the effect
  42955. */
  42956. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42957. if (defines["INSTANCES"]) {
  42958. attribs.push("world0");
  42959. attribs.push("world1");
  42960. attribs.push("world2");
  42961. attribs.push("world3");
  42962. }
  42963. };
  42964. /**
  42965. * Binds the light shadow information to the effect for the given mesh.
  42966. * @param light The light containing the generator
  42967. * @param scene The scene the lights belongs to
  42968. * @param mesh The mesh we are binding the information to render
  42969. * @param lightIndex The light index in the effect used to render the mesh
  42970. * @param effect The effect we are binding the data to
  42971. */
  42972. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42973. if (light.shadowEnabled && mesh.receiveShadows) {
  42974. var shadowGenerator = light.getShadowGenerator();
  42975. if (shadowGenerator) {
  42976. shadowGenerator.bindShadowLight(lightIndex, effect);
  42977. }
  42978. }
  42979. };
  42980. /**
  42981. * Binds the light information to the effect.
  42982. * @param light The light containing the generator
  42983. * @param effect The effect we are binding the data to
  42984. * @param lightIndex The light index in the effect used to render
  42985. */
  42986. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42987. light.transferToEffect(effect, lightIndex + "");
  42988. };
  42989. /**
  42990. * Binds the lights information from the scene to the effect for the given mesh.
  42991. * @param scene The scene the lights belongs to
  42992. * @param mesh The mesh we are binding the information to render
  42993. * @param effect The effect we are binding the data to
  42994. * @param defines The generated defines for the effect
  42995. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42996. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42997. */
  42998. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42999. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43000. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43001. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43002. for (var i = 0; i < len; i++) {
  43003. var light = mesh._lightSources[i];
  43004. var iAsString = i.toString();
  43005. var scaledIntensity = light.getScaledIntensity();
  43006. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43007. MaterialHelper.BindLightProperties(light, effect, i);
  43008. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43009. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43010. if (defines["SPECULARTERM"]) {
  43011. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43012. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43013. }
  43014. // Shadows
  43015. if (scene.shadowsEnabled) {
  43016. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43017. }
  43018. light._uniformBuffer.update();
  43019. }
  43020. };
  43021. /**
  43022. * Binds the fog information from the scene to the effect for the given mesh.
  43023. * @param scene The scene the lights belongs to
  43024. * @param mesh The mesh we are binding the information to render
  43025. * @param effect The effect we are binding the data to
  43026. */
  43027. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43028. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43029. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43030. effect.setColor3("vFogColor", scene.fogColor);
  43031. }
  43032. };
  43033. /**
  43034. * Binds the bones information from the mesh to the effect.
  43035. * @param mesh The mesh we are binding the information to render
  43036. * @param effect The effect we are binding the data to
  43037. */
  43038. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43039. if (!effect || !mesh) {
  43040. return;
  43041. }
  43042. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43043. mesh.computeBonesUsingShaders = false;
  43044. }
  43045. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43046. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43047. if (matrices) {
  43048. effect.setMatrices("mBones", matrices);
  43049. }
  43050. }
  43051. };
  43052. /**
  43053. * Binds the morph targets information from the mesh to the effect.
  43054. * @param abstractMesh The mesh we are binding the information to render
  43055. * @param effect The effect we are binding the data to
  43056. */
  43057. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43058. var manager = abstractMesh.morphTargetManager;
  43059. if (!abstractMesh || !manager) {
  43060. return;
  43061. }
  43062. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43063. };
  43064. /**
  43065. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43066. * @param defines The generated defines used in the effect
  43067. * @param effect The effect we are binding the data to
  43068. * @param scene The scene we are willing to render with logarithmic scale for
  43069. */
  43070. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43071. if (defines["LOGARITHMICDEPTH"]) {
  43072. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43073. }
  43074. };
  43075. /**
  43076. * Binds the clip plane information from the scene to the effect.
  43077. * @param scene The scene the clip plane information are extracted from
  43078. * @param effect The effect we are binding the data to
  43079. */
  43080. MaterialHelper.BindClipPlane = function (effect, scene) {
  43081. if (scene.clipPlane) {
  43082. var clipPlane = scene.clipPlane;
  43083. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43084. }
  43085. };
  43086. return MaterialHelper;
  43087. }());
  43088. BABYLON.MaterialHelper = MaterialHelper;
  43089. })(BABYLON || (BABYLON = {}));
  43090. //# sourceMappingURL=babylon.materialHelper.js.map
  43091. var BABYLON;
  43092. (function (BABYLON) {
  43093. var PushMaterial = /** @class */ (function (_super) {
  43094. __extends(PushMaterial, _super);
  43095. function PushMaterial(name, scene) {
  43096. var _this = _super.call(this, name, scene) || this;
  43097. _this._normalMatrix = new BABYLON.Matrix();
  43098. _this.storeEffectOnSubMeshes = true;
  43099. return _this;
  43100. }
  43101. PushMaterial.prototype.getEffect = function () {
  43102. return this._activeEffect;
  43103. };
  43104. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43105. if (!mesh) {
  43106. return false;
  43107. }
  43108. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43109. return true;
  43110. }
  43111. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43112. };
  43113. /**
  43114. * Binds the given world matrix to the active effect
  43115. *
  43116. * @param world the matrix to bind
  43117. */
  43118. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43119. this._activeEffect.setMatrix("world", world);
  43120. };
  43121. /**
  43122. * Binds the given normal matrix to the active effect
  43123. *
  43124. * @param normalMatrix the matrix to bind
  43125. */
  43126. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43127. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43128. };
  43129. PushMaterial.prototype.bind = function (world, mesh) {
  43130. if (!mesh) {
  43131. return;
  43132. }
  43133. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43134. };
  43135. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43136. if (effect === void 0) { effect = null; }
  43137. _super.prototype._afterBind.call(this, mesh);
  43138. this.getScene()._cachedEffect = effect;
  43139. };
  43140. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43141. if (visibility === void 0) { visibility = 1; }
  43142. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43143. };
  43144. return PushMaterial;
  43145. }(BABYLON.Material));
  43146. BABYLON.PushMaterial = PushMaterial;
  43147. })(BABYLON || (BABYLON = {}));
  43148. //# sourceMappingURL=babylon.pushMaterial.js.map
  43149. var BABYLON;
  43150. (function (BABYLON) {
  43151. /** @hidden */
  43152. var StandardMaterialDefines = /** @class */ (function (_super) {
  43153. __extends(StandardMaterialDefines, _super);
  43154. function StandardMaterialDefines() {
  43155. var _this = _super.call(this) || this;
  43156. _this.MAINUV1 = false;
  43157. _this.MAINUV2 = false;
  43158. _this.DIFFUSE = false;
  43159. _this.DIFFUSEDIRECTUV = 0;
  43160. _this.AMBIENT = false;
  43161. _this.AMBIENTDIRECTUV = 0;
  43162. _this.OPACITY = false;
  43163. _this.OPACITYDIRECTUV = 0;
  43164. _this.OPACITYRGB = false;
  43165. _this.REFLECTION = false;
  43166. _this.EMISSIVE = false;
  43167. _this.EMISSIVEDIRECTUV = 0;
  43168. _this.SPECULAR = false;
  43169. _this.SPECULARDIRECTUV = 0;
  43170. _this.BUMP = false;
  43171. _this.BUMPDIRECTUV = 0;
  43172. _this.PARALLAX = false;
  43173. _this.PARALLAXOCCLUSION = false;
  43174. _this.SPECULAROVERALPHA = false;
  43175. _this.CLIPPLANE = false;
  43176. _this.ALPHATEST = false;
  43177. _this.DEPTHPREPASS = false;
  43178. _this.ALPHAFROMDIFFUSE = false;
  43179. _this.POINTSIZE = false;
  43180. _this.FOG = false;
  43181. _this.SPECULARTERM = false;
  43182. _this.DIFFUSEFRESNEL = false;
  43183. _this.OPACITYFRESNEL = false;
  43184. _this.REFLECTIONFRESNEL = false;
  43185. _this.REFRACTIONFRESNEL = false;
  43186. _this.EMISSIVEFRESNEL = false;
  43187. _this.FRESNEL = false;
  43188. _this.NORMAL = false;
  43189. _this.UV1 = false;
  43190. _this.UV2 = false;
  43191. _this.VERTEXCOLOR = false;
  43192. _this.VERTEXALPHA = false;
  43193. _this.NUM_BONE_INFLUENCERS = 0;
  43194. _this.BonesPerMesh = 0;
  43195. _this.INSTANCES = false;
  43196. _this.GLOSSINESS = false;
  43197. _this.ROUGHNESS = false;
  43198. _this.EMISSIVEASILLUMINATION = false;
  43199. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43200. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43201. _this.LIGHTMAP = false;
  43202. _this.LIGHTMAPDIRECTUV = 0;
  43203. _this.OBJECTSPACE_NORMALMAP = false;
  43204. _this.USELIGHTMAPASSHADOWMAP = false;
  43205. _this.REFLECTIONMAP_3D = false;
  43206. _this.REFLECTIONMAP_SPHERICAL = false;
  43207. _this.REFLECTIONMAP_PLANAR = false;
  43208. _this.REFLECTIONMAP_CUBIC = false;
  43209. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43210. _this.REFLECTIONMAP_PROJECTION = false;
  43211. _this.REFLECTIONMAP_SKYBOX = false;
  43212. _this.REFLECTIONMAP_EXPLICIT = false;
  43213. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43214. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43215. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43216. _this.INVERTCUBICMAP = false;
  43217. _this.LOGARITHMICDEPTH = false;
  43218. _this.REFRACTION = false;
  43219. _this.REFRACTIONMAP_3D = false;
  43220. _this.REFLECTIONOVERALPHA = false;
  43221. _this.TWOSIDEDLIGHTING = false;
  43222. _this.SHADOWFLOAT = false;
  43223. _this.MORPHTARGETS = false;
  43224. _this.MORPHTARGETS_NORMAL = false;
  43225. _this.MORPHTARGETS_TANGENT = false;
  43226. _this.NUM_MORPH_INFLUENCERS = 0;
  43227. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43228. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43229. _this.IMAGEPROCESSING = false;
  43230. _this.VIGNETTE = false;
  43231. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43232. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43233. _this.TONEMAPPING = false;
  43234. _this.CONTRAST = false;
  43235. _this.COLORCURVES = false;
  43236. _this.COLORGRADING = false;
  43237. _this.COLORGRADING3D = false;
  43238. _this.SAMPLER3DGREENDEPTH = false;
  43239. _this.SAMPLER3DBGRMAP = false;
  43240. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43241. /**
  43242. * If the reflection texture on this material is in linear color space
  43243. * @hidden
  43244. */
  43245. _this.IS_REFLECTION_LINEAR = false;
  43246. /**
  43247. * If the refraction texture on this material is in linear color space
  43248. * @hidden
  43249. */
  43250. _this.IS_REFRACTION_LINEAR = false;
  43251. _this.EXPOSURE = false;
  43252. _this.rebuild();
  43253. return _this;
  43254. }
  43255. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43256. var modes = [
  43257. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43258. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43259. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43260. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43261. ];
  43262. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43263. var mode = modes_1[_i];
  43264. this[mode] = (mode === modeToEnable);
  43265. }
  43266. };
  43267. return StandardMaterialDefines;
  43268. }(BABYLON.MaterialDefines));
  43269. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43270. var StandardMaterial = /** @class */ (function (_super) {
  43271. __extends(StandardMaterial, _super);
  43272. function StandardMaterial(name, scene) {
  43273. var _this = _super.call(this, name, scene) || this;
  43274. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43275. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43276. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43277. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43278. _this.specularPower = 64;
  43279. _this._useAlphaFromDiffuseTexture = false;
  43280. _this._useEmissiveAsIllumination = false;
  43281. _this._linkEmissiveWithDiffuse = false;
  43282. _this._useSpecularOverAlpha = false;
  43283. _this._useReflectionOverAlpha = false;
  43284. _this._disableLighting = false;
  43285. _this._useObjectSpaceNormalMap = false;
  43286. _this._useParallax = false;
  43287. _this._useParallaxOcclusion = false;
  43288. _this.parallaxScaleBias = 0.05;
  43289. _this._roughness = 0;
  43290. _this.indexOfRefraction = 0.98;
  43291. _this.invertRefractionY = true;
  43292. /**
  43293. * Defines the alpha limits in alpha test mode
  43294. */
  43295. _this.alphaCutOff = 0.4;
  43296. _this._useLightmapAsShadowmap = false;
  43297. _this._useReflectionFresnelFromSpecular = false;
  43298. _this._useGlossinessFromSpecularMapAlpha = false;
  43299. _this._maxSimultaneousLights = 4;
  43300. /**
  43301. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43302. */
  43303. _this._invertNormalMapX = false;
  43304. /**
  43305. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43306. */
  43307. _this._invertNormalMapY = false;
  43308. /**
  43309. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43310. */
  43311. _this._twoSidedLighting = false;
  43312. _this._renderTargets = new BABYLON.SmartArray(16);
  43313. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43314. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43315. // Setup the default processing configuration to the scene.
  43316. _this._attachImageProcessingConfiguration(null);
  43317. _this.getRenderTargetTextures = function () {
  43318. _this._renderTargets.reset();
  43319. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43320. _this._renderTargets.push(_this._reflectionTexture);
  43321. }
  43322. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43323. _this._renderTargets.push(_this._refractionTexture);
  43324. }
  43325. return _this._renderTargets;
  43326. };
  43327. return _this;
  43328. }
  43329. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43330. /**
  43331. * Gets the image processing configuration used either in this material.
  43332. */
  43333. get: function () {
  43334. return this._imageProcessingConfiguration;
  43335. },
  43336. /**
  43337. * Sets the Default image processing configuration used either in the this material.
  43338. *
  43339. * If sets to null, the scene one is in use.
  43340. */
  43341. set: function (value) {
  43342. this._attachImageProcessingConfiguration(value);
  43343. // Ensure the effect will be rebuilt.
  43344. this._markAllSubMeshesAsTexturesDirty();
  43345. },
  43346. enumerable: true,
  43347. configurable: true
  43348. });
  43349. /**
  43350. * Attaches a new image processing configuration to the Standard Material.
  43351. * @param configuration
  43352. */
  43353. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43354. var _this = this;
  43355. if (configuration === this._imageProcessingConfiguration) {
  43356. return;
  43357. }
  43358. // Detaches observer.
  43359. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43360. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43361. }
  43362. // Pick the scene configuration if needed.
  43363. if (!configuration) {
  43364. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43365. }
  43366. else {
  43367. this._imageProcessingConfiguration = configuration;
  43368. }
  43369. // Attaches observer.
  43370. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43371. _this._markAllSubMeshesAsImageProcessingDirty();
  43372. });
  43373. };
  43374. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43375. /**
  43376. * Gets wether the color curves effect is enabled.
  43377. */
  43378. get: function () {
  43379. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43380. },
  43381. /**
  43382. * Sets wether the color curves effect is enabled.
  43383. */
  43384. set: function (value) {
  43385. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43386. },
  43387. enumerable: true,
  43388. configurable: true
  43389. });
  43390. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43391. /**
  43392. * Gets wether the color grading effect is enabled.
  43393. */
  43394. get: function () {
  43395. return this.imageProcessingConfiguration.colorGradingEnabled;
  43396. },
  43397. /**
  43398. * Gets wether the color grading effect is enabled.
  43399. */
  43400. set: function (value) {
  43401. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43402. },
  43403. enumerable: true,
  43404. configurable: true
  43405. });
  43406. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43407. /**
  43408. * Gets wether tonemapping is enabled or not.
  43409. */
  43410. get: function () {
  43411. return this._imageProcessingConfiguration.toneMappingEnabled;
  43412. },
  43413. /**
  43414. * Sets wether tonemapping is enabled or not
  43415. */
  43416. set: function (value) {
  43417. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. ;
  43423. ;
  43424. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43425. /**
  43426. * The camera exposure used on this material.
  43427. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43428. * This corresponds to a photographic exposure.
  43429. */
  43430. get: function () {
  43431. return this._imageProcessingConfiguration.exposure;
  43432. },
  43433. /**
  43434. * The camera exposure used on this material.
  43435. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43436. * This corresponds to a photographic exposure.
  43437. */
  43438. set: function (value) {
  43439. this._imageProcessingConfiguration.exposure = value;
  43440. },
  43441. enumerable: true,
  43442. configurable: true
  43443. });
  43444. ;
  43445. ;
  43446. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43447. /**
  43448. * Gets The camera contrast used on this material.
  43449. */
  43450. get: function () {
  43451. return this._imageProcessingConfiguration.contrast;
  43452. },
  43453. /**
  43454. * Sets The camera contrast used on this material.
  43455. */
  43456. set: function (value) {
  43457. this._imageProcessingConfiguration.contrast = value;
  43458. },
  43459. enumerable: true,
  43460. configurable: true
  43461. });
  43462. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43463. /**
  43464. * Gets the Color Grading 2D Lookup Texture.
  43465. */
  43466. get: function () {
  43467. return this._imageProcessingConfiguration.colorGradingTexture;
  43468. },
  43469. /**
  43470. * Sets the Color Grading 2D Lookup Texture.
  43471. */
  43472. set: function (value) {
  43473. this._imageProcessingConfiguration.colorGradingTexture = value;
  43474. },
  43475. enumerable: true,
  43476. configurable: true
  43477. });
  43478. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43479. /**
  43480. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43481. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43482. * 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;
  43483. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43484. */
  43485. get: function () {
  43486. return this._imageProcessingConfiguration.colorCurves;
  43487. },
  43488. /**
  43489. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43490. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43491. * 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;
  43492. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43493. */
  43494. set: function (value) {
  43495. this._imageProcessingConfiguration.colorCurves = value;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. StandardMaterial.prototype.getClassName = function () {
  43501. return "StandardMaterial";
  43502. };
  43503. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43504. get: function () {
  43505. return this._useLogarithmicDepth;
  43506. },
  43507. set: function (value) {
  43508. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43509. this._markAllSubMeshesAsMiscDirty();
  43510. },
  43511. enumerable: true,
  43512. configurable: true
  43513. });
  43514. StandardMaterial.prototype.needAlphaBlending = function () {
  43515. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43516. };
  43517. StandardMaterial.prototype.needAlphaTesting = function () {
  43518. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43519. };
  43520. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43521. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43522. };
  43523. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43524. return this._diffuseTexture;
  43525. };
  43526. /**
  43527. * Child classes can use it to update shaders
  43528. */
  43529. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43530. if (useInstances === void 0) { useInstances = false; }
  43531. if (subMesh.effect && this.isFrozen) {
  43532. if (this._wasPreviouslyReady && subMesh.effect) {
  43533. return true;
  43534. }
  43535. }
  43536. if (!subMesh._materialDefines) {
  43537. subMesh._materialDefines = new StandardMaterialDefines();
  43538. }
  43539. var scene = this.getScene();
  43540. var defines = subMesh._materialDefines;
  43541. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43542. if (defines._renderId === scene.getRenderId()) {
  43543. return true;
  43544. }
  43545. }
  43546. var engine = scene.getEngine();
  43547. // Lights
  43548. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43549. // Textures
  43550. if (defines._areTexturesDirty) {
  43551. defines._needUVs = false;
  43552. defines.MAINUV1 = false;
  43553. defines.MAINUV2 = false;
  43554. if (scene.texturesEnabled) {
  43555. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43556. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43557. return false;
  43558. }
  43559. else {
  43560. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43561. }
  43562. }
  43563. else {
  43564. defines.DIFFUSE = false;
  43565. }
  43566. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43567. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43568. return false;
  43569. }
  43570. else {
  43571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43572. }
  43573. }
  43574. else {
  43575. defines.AMBIENT = false;
  43576. }
  43577. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43578. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43579. return false;
  43580. }
  43581. else {
  43582. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43583. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43584. }
  43585. }
  43586. else {
  43587. defines.OPACITY = false;
  43588. }
  43589. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43590. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43591. return false;
  43592. }
  43593. else {
  43594. defines._needNormals = true;
  43595. defines.REFLECTION = true;
  43596. defines.ROUGHNESS = (this._roughness > 0);
  43597. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43598. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43599. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43600. switch (this._reflectionTexture.coordinatesMode) {
  43601. case BABYLON.Texture.EXPLICIT_MODE:
  43602. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43603. break;
  43604. case BABYLON.Texture.PLANAR_MODE:
  43605. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43606. break;
  43607. case BABYLON.Texture.PROJECTION_MODE:
  43608. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43609. break;
  43610. case BABYLON.Texture.SKYBOX_MODE:
  43611. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43612. break;
  43613. case BABYLON.Texture.SPHERICAL_MODE:
  43614. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43615. break;
  43616. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43617. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43618. break;
  43619. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43620. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43621. break;
  43622. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43623. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43624. break;
  43625. case BABYLON.Texture.CUBIC_MODE:
  43626. case BABYLON.Texture.INVCUBIC_MODE:
  43627. default:
  43628. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43629. break;
  43630. }
  43631. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43632. }
  43633. }
  43634. else {
  43635. defines.REFLECTION = false;
  43636. }
  43637. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43638. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43639. return false;
  43640. }
  43641. else {
  43642. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43643. }
  43644. }
  43645. else {
  43646. defines.EMISSIVE = false;
  43647. }
  43648. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43649. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43650. return false;
  43651. }
  43652. else {
  43653. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43654. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43655. }
  43656. }
  43657. else {
  43658. defines.LIGHTMAP = false;
  43659. }
  43660. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43661. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43662. return false;
  43663. }
  43664. else {
  43665. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43666. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43667. }
  43668. }
  43669. else {
  43670. defines.SPECULAR = false;
  43671. }
  43672. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43673. // Bump texure can not be not blocking.
  43674. if (!this._bumpTexture.isReady()) {
  43675. return false;
  43676. }
  43677. else {
  43678. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43679. defines.PARALLAX = this._useParallax;
  43680. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43681. }
  43682. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43683. }
  43684. else {
  43685. defines.BUMP = false;
  43686. }
  43687. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43688. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43689. return false;
  43690. }
  43691. else {
  43692. defines._needUVs = true;
  43693. defines.REFRACTION = true;
  43694. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43695. }
  43696. }
  43697. else {
  43698. defines.REFRACTION = false;
  43699. }
  43700. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43701. }
  43702. else {
  43703. defines.DIFFUSE = false;
  43704. defines.AMBIENT = false;
  43705. defines.OPACITY = false;
  43706. defines.REFLECTION = false;
  43707. defines.EMISSIVE = false;
  43708. defines.LIGHTMAP = false;
  43709. defines.BUMP = false;
  43710. defines.REFRACTION = false;
  43711. }
  43712. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43713. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43714. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43715. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43716. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43717. }
  43718. if (defines._areImageProcessingDirty) {
  43719. if (!this._imageProcessingConfiguration.isReady()) {
  43720. return false;
  43721. }
  43722. this._imageProcessingConfiguration.prepareDefines(defines);
  43723. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43724. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43725. }
  43726. if (defines._areFresnelDirty) {
  43727. if (StandardMaterial.FresnelEnabled) {
  43728. // Fresnel
  43729. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43730. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43731. this._reflectionFresnelParameters) {
  43732. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43733. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43734. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43735. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43736. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43737. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43738. defines._needNormals = true;
  43739. defines.FRESNEL = true;
  43740. }
  43741. }
  43742. else {
  43743. defines.FRESNEL = false;
  43744. }
  43745. }
  43746. // Misc.
  43747. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43748. // Attribs
  43749. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43750. // Values that need to be evaluated on every frame
  43751. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43752. // Get correct effect
  43753. if (defines.isDirty) {
  43754. defines.markAsProcessed();
  43755. scene.resetCachedMaterial();
  43756. // Fallbacks
  43757. var fallbacks = new BABYLON.EffectFallbacks();
  43758. if (defines.REFLECTION) {
  43759. fallbacks.addFallback(0, "REFLECTION");
  43760. }
  43761. if (defines.SPECULAR) {
  43762. fallbacks.addFallback(0, "SPECULAR");
  43763. }
  43764. if (defines.BUMP) {
  43765. fallbacks.addFallback(0, "BUMP");
  43766. }
  43767. if (defines.PARALLAX) {
  43768. fallbacks.addFallback(1, "PARALLAX");
  43769. }
  43770. if (defines.PARALLAXOCCLUSION) {
  43771. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43772. }
  43773. if (defines.SPECULAROVERALPHA) {
  43774. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43775. }
  43776. if (defines.FOG) {
  43777. fallbacks.addFallback(1, "FOG");
  43778. }
  43779. if (defines.POINTSIZE) {
  43780. fallbacks.addFallback(0, "POINTSIZE");
  43781. }
  43782. if (defines.LOGARITHMICDEPTH) {
  43783. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43784. }
  43785. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43786. if (defines.SPECULARTERM) {
  43787. fallbacks.addFallback(0, "SPECULARTERM");
  43788. }
  43789. if (defines.DIFFUSEFRESNEL) {
  43790. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43791. }
  43792. if (defines.OPACITYFRESNEL) {
  43793. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43794. }
  43795. if (defines.REFLECTIONFRESNEL) {
  43796. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43797. }
  43798. if (defines.EMISSIVEFRESNEL) {
  43799. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43800. }
  43801. if (defines.FRESNEL) {
  43802. fallbacks.addFallback(4, "FRESNEL");
  43803. }
  43804. //Attributes
  43805. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43806. if (defines.NORMAL) {
  43807. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43808. }
  43809. if (defines.UV1) {
  43810. attribs.push(BABYLON.VertexBuffer.UVKind);
  43811. }
  43812. if (defines.UV2) {
  43813. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43814. }
  43815. if (defines.VERTEXCOLOR) {
  43816. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43817. }
  43818. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43819. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43820. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43821. var shaderName = "default";
  43822. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43823. "vFogInfos", "vFogColor", "pointSize",
  43824. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43825. "mBones",
  43826. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43827. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43828. "vReflectionPosition", "vReflectionSize",
  43829. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43830. ];
  43831. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43832. var uniformBuffers = ["Material", "Scene"];
  43833. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43834. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43835. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43836. uniformsNames: uniforms,
  43837. uniformBuffersNames: uniformBuffers,
  43838. samplers: samplers,
  43839. defines: defines,
  43840. maxSimultaneousLights: this._maxSimultaneousLights
  43841. });
  43842. if (this.customShaderNameResolve) {
  43843. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43844. }
  43845. var join = defines.toString();
  43846. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43847. attributes: attribs,
  43848. uniformsNames: uniforms,
  43849. uniformBuffersNames: uniformBuffers,
  43850. samplers: samplers,
  43851. defines: join,
  43852. fallbacks: fallbacks,
  43853. onCompiled: this.onCompiled,
  43854. onError: this.onError,
  43855. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43856. }, engine), defines);
  43857. this.buildUniformLayout();
  43858. }
  43859. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43860. return false;
  43861. }
  43862. defines._renderId = scene.getRenderId();
  43863. this._wasPreviouslyReady = true;
  43864. return true;
  43865. };
  43866. StandardMaterial.prototype.buildUniformLayout = function () {
  43867. // Order is important !
  43868. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43869. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43870. this._uniformBuffer.addUniform("opacityParts", 4);
  43871. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43872. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43873. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43874. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43875. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43876. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43877. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43878. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43879. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43880. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43881. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43882. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43883. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43884. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43885. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43886. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43887. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43888. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43889. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43890. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43891. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43892. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43893. this._uniformBuffer.addUniform("specularMatrix", 16);
  43894. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43895. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43896. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43897. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43898. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43899. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43900. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43901. this._uniformBuffer.addUniform("pointSize", 1);
  43902. this._uniformBuffer.create();
  43903. };
  43904. StandardMaterial.prototype.unbind = function () {
  43905. if (this._activeEffect) {
  43906. var needFlag = false;
  43907. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43908. this._activeEffect.setTexture("reflection2DSampler", null);
  43909. needFlag = true;
  43910. }
  43911. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43912. this._activeEffect.setTexture("refraction2DSampler", null);
  43913. needFlag = true;
  43914. }
  43915. if (needFlag) {
  43916. this._markAllSubMeshesAsTexturesDirty();
  43917. }
  43918. }
  43919. _super.prototype.unbind.call(this);
  43920. };
  43921. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43922. var scene = this.getScene();
  43923. var defines = subMesh._materialDefines;
  43924. if (!defines) {
  43925. return;
  43926. }
  43927. var effect = subMesh.effect;
  43928. if (!effect) {
  43929. return;
  43930. }
  43931. this._activeEffect = effect;
  43932. // Matrices
  43933. this.bindOnlyWorldMatrix(world);
  43934. // Normal Matrix
  43935. if (defines.OBJECTSPACE_NORMALMAP) {
  43936. world.toNormalMatrix(this._normalMatrix);
  43937. this.bindOnlyNormalMatrix(this._normalMatrix);
  43938. }
  43939. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43940. // Bones
  43941. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43942. if (mustRebind) {
  43943. this._uniformBuffer.bindToEffect(effect, "Material");
  43944. this.bindViewProjection(effect);
  43945. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43946. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43947. // Fresnel
  43948. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43949. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43950. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43951. }
  43952. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43953. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43954. }
  43955. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43956. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43957. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43958. }
  43959. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43960. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43961. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43962. }
  43963. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43964. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43965. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43966. }
  43967. }
  43968. // Textures
  43969. if (scene.texturesEnabled) {
  43970. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43971. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43972. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43973. if (this._diffuseTexture.hasAlpha) {
  43974. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43975. }
  43976. }
  43977. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43978. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43979. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43980. }
  43981. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43982. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43983. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43984. }
  43985. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43986. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43987. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43988. if (this._reflectionTexture.boundingBoxSize) {
  43989. var cubeTexture = this._reflectionTexture;
  43990. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43991. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43992. }
  43993. }
  43994. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43995. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43996. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43997. }
  43998. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43999. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44000. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44001. }
  44002. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44003. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44004. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44005. }
  44006. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44007. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44008. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44009. if (scene._mirroredCameraPosition) {
  44010. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44011. }
  44012. else {
  44013. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44014. }
  44015. }
  44016. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44017. var depth = 1.0;
  44018. if (!this._refractionTexture.isCube) {
  44019. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44020. if (this._refractionTexture.depth) {
  44021. depth = this._refractionTexture.depth;
  44022. }
  44023. }
  44024. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44025. }
  44026. }
  44027. // Point size
  44028. if (this.pointsCloud) {
  44029. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44030. }
  44031. if (defines.SPECULARTERM) {
  44032. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44033. }
  44034. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44035. // Diffuse
  44036. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44037. }
  44038. // Textures
  44039. if (scene.texturesEnabled) {
  44040. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44041. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44042. }
  44043. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44044. effect.setTexture("ambientSampler", this._ambientTexture);
  44045. }
  44046. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44047. effect.setTexture("opacitySampler", this._opacityTexture);
  44048. }
  44049. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44050. if (this._reflectionTexture.isCube) {
  44051. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44052. }
  44053. else {
  44054. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44055. }
  44056. }
  44057. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44058. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44059. }
  44060. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44061. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44062. }
  44063. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44064. effect.setTexture("specularSampler", this._specularTexture);
  44065. }
  44066. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44067. effect.setTexture("bumpSampler", this._bumpTexture);
  44068. }
  44069. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44070. var depth = 1.0;
  44071. if (this._refractionTexture.isCube) {
  44072. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44073. }
  44074. else {
  44075. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44076. }
  44077. }
  44078. }
  44079. // Clip plane
  44080. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44081. // Colors
  44082. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44083. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44084. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44085. }
  44086. if (mustRebind || !this.isFrozen) {
  44087. // Lights
  44088. if (scene.lightsEnabled && !this._disableLighting) {
  44089. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44090. }
  44091. // View
  44092. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44093. this.bindView(effect);
  44094. }
  44095. // Fog
  44096. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44097. // Morph targets
  44098. if (defines.NUM_MORPH_INFLUENCERS) {
  44099. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44100. }
  44101. // Log. depth
  44102. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44103. // image processing
  44104. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44105. this._imageProcessingConfiguration.bind(this._activeEffect);
  44106. }
  44107. }
  44108. this._uniformBuffer.update();
  44109. this._afterBind(mesh, this._activeEffect);
  44110. };
  44111. StandardMaterial.prototype.getAnimatables = function () {
  44112. var results = [];
  44113. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44114. results.push(this._diffuseTexture);
  44115. }
  44116. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44117. results.push(this._ambientTexture);
  44118. }
  44119. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44120. results.push(this._opacityTexture);
  44121. }
  44122. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44123. results.push(this._reflectionTexture);
  44124. }
  44125. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44126. results.push(this._emissiveTexture);
  44127. }
  44128. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44129. results.push(this._specularTexture);
  44130. }
  44131. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44132. results.push(this._bumpTexture);
  44133. }
  44134. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44135. results.push(this._lightmapTexture);
  44136. }
  44137. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44138. results.push(this._refractionTexture);
  44139. }
  44140. return results;
  44141. };
  44142. StandardMaterial.prototype.getActiveTextures = function () {
  44143. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44144. if (this._diffuseTexture) {
  44145. activeTextures.push(this._diffuseTexture);
  44146. }
  44147. if (this._ambientTexture) {
  44148. activeTextures.push(this._ambientTexture);
  44149. }
  44150. if (this._opacityTexture) {
  44151. activeTextures.push(this._opacityTexture);
  44152. }
  44153. if (this._reflectionTexture) {
  44154. activeTextures.push(this._reflectionTexture);
  44155. }
  44156. if (this._emissiveTexture) {
  44157. activeTextures.push(this._emissiveTexture);
  44158. }
  44159. if (this._specularTexture) {
  44160. activeTextures.push(this._specularTexture);
  44161. }
  44162. if (this._bumpTexture) {
  44163. activeTextures.push(this._bumpTexture);
  44164. }
  44165. if (this._lightmapTexture) {
  44166. activeTextures.push(this._lightmapTexture);
  44167. }
  44168. if (this._refractionTexture) {
  44169. activeTextures.push(this._refractionTexture);
  44170. }
  44171. return activeTextures;
  44172. };
  44173. StandardMaterial.prototype.hasTexture = function (texture) {
  44174. if (_super.prototype.hasTexture.call(this, texture)) {
  44175. return true;
  44176. }
  44177. if (this._diffuseTexture === texture) {
  44178. return true;
  44179. }
  44180. if (this._ambientTexture === texture) {
  44181. return true;
  44182. }
  44183. if (this._opacityTexture === texture) {
  44184. return true;
  44185. }
  44186. if (this._reflectionTexture === texture) {
  44187. return true;
  44188. }
  44189. if (this._emissiveTexture === texture) {
  44190. return true;
  44191. }
  44192. if (this._specularTexture === texture) {
  44193. return true;
  44194. }
  44195. if (this._bumpTexture === texture) {
  44196. return true;
  44197. }
  44198. if (this._lightmapTexture === texture) {
  44199. return true;
  44200. }
  44201. if (this._refractionTexture === texture) {
  44202. return true;
  44203. }
  44204. return false;
  44205. };
  44206. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44207. if (forceDisposeTextures) {
  44208. if (this._diffuseTexture) {
  44209. this._diffuseTexture.dispose();
  44210. }
  44211. if (this._ambientTexture) {
  44212. this._ambientTexture.dispose();
  44213. }
  44214. if (this._opacityTexture) {
  44215. this._opacityTexture.dispose();
  44216. }
  44217. if (this._reflectionTexture) {
  44218. this._reflectionTexture.dispose();
  44219. }
  44220. if (this._emissiveTexture) {
  44221. this._emissiveTexture.dispose();
  44222. }
  44223. if (this._specularTexture) {
  44224. this._specularTexture.dispose();
  44225. }
  44226. if (this._bumpTexture) {
  44227. this._bumpTexture.dispose();
  44228. }
  44229. if (this._lightmapTexture) {
  44230. this._lightmapTexture.dispose();
  44231. }
  44232. if (this._refractionTexture) {
  44233. this._refractionTexture.dispose();
  44234. }
  44235. }
  44236. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44237. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44238. }
  44239. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44240. };
  44241. StandardMaterial.prototype.clone = function (name) {
  44242. var _this = this;
  44243. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44244. result.name = name;
  44245. result.id = name;
  44246. return result;
  44247. };
  44248. StandardMaterial.prototype.serialize = function () {
  44249. return BABYLON.SerializationHelper.Serialize(this);
  44250. };
  44251. // Statics
  44252. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44253. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44254. };
  44255. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44256. get: function () {
  44257. return StandardMaterial._DiffuseTextureEnabled;
  44258. },
  44259. set: function (value) {
  44260. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44261. return;
  44262. }
  44263. StandardMaterial._DiffuseTextureEnabled = value;
  44264. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44265. },
  44266. enumerable: true,
  44267. configurable: true
  44268. });
  44269. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44270. get: function () {
  44271. return StandardMaterial._AmbientTextureEnabled;
  44272. },
  44273. set: function (value) {
  44274. if (StandardMaterial._AmbientTextureEnabled === value) {
  44275. return;
  44276. }
  44277. StandardMaterial._AmbientTextureEnabled = value;
  44278. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44279. },
  44280. enumerable: true,
  44281. configurable: true
  44282. });
  44283. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44284. get: function () {
  44285. return StandardMaterial._OpacityTextureEnabled;
  44286. },
  44287. set: function (value) {
  44288. if (StandardMaterial._OpacityTextureEnabled === value) {
  44289. return;
  44290. }
  44291. StandardMaterial._OpacityTextureEnabled = value;
  44292. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44293. },
  44294. enumerable: true,
  44295. configurable: true
  44296. });
  44297. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44298. get: function () {
  44299. return StandardMaterial._ReflectionTextureEnabled;
  44300. },
  44301. set: function (value) {
  44302. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44303. return;
  44304. }
  44305. StandardMaterial._ReflectionTextureEnabled = value;
  44306. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44312. get: function () {
  44313. return StandardMaterial._EmissiveTextureEnabled;
  44314. },
  44315. set: function (value) {
  44316. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44317. return;
  44318. }
  44319. StandardMaterial._EmissiveTextureEnabled = value;
  44320. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44321. },
  44322. enumerable: true,
  44323. configurable: true
  44324. });
  44325. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44326. get: function () {
  44327. return StandardMaterial._SpecularTextureEnabled;
  44328. },
  44329. set: function (value) {
  44330. if (StandardMaterial._SpecularTextureEnabled === value) {
  44331. return;
  44332. }
  44333. StandardMaterial._SpecularTextureEnabled = value;
  44334. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44335. },
  44336. enumerable: true,
  44337. configurable: true
  44338. });
  44339. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44340. get: function () {
  44341. return StandardMaterial._BumpTextureEnabled;
  44342. },
  44343. set: function (value) {
  44344. if (StandardMaterial._BumpTextureEnabled === value) {
  44345. return;
  44346. }
  44347. StandardMaterial._BumpTextureEnabled = value;
  44348. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44349. },
  44350. enumerable: true,
  44351. configurable: true
  44352. });
  44353. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44354. get: function () {
  44355. return StandardMaterial._LightmapTextureEnabled;
  44356. },
  44357. set: function (value) {
  44358. if (StandardMaterial._LightmapTextureEnabled === value) {
  44359. return;
  44360. }
  44361. StandardMaterial._LightmapTextureEnabled = value;
  44362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44363. },
  44364. enumerable: true,
  44365. configurable: true
  44366. });
  44367. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44368. get: function () {
  44369. return StandardMaterial._RefractionTextureEnabled;
  44370. },
  44371. set: function (value) {
  44372. if (StandardMaterial._RefractionTextureEnabled === value) {
  44373. return;
  44374. }
  44375. StandardMaterial._RefractionTextureEnabled = value;
  44376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44377. },
  44378. enumerable: true,
  44379. configurable: true
  44380. });
  44381. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44382. get: function () {
  44383. return StandardMaterial._ColorGradingTextureEnabled;
  44384. },
  44385. set: function (value) {
  44386. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44387. return;
  44388. }
  44389. StandardMaterial._ColorGradingTextureEnabled = value;
  44390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44396. get: function () {
  44397. return StandardMaterial._FresnelEnabled;
  44398. },
  44399. set: function (value) {
  44400. if (StandardMaterial._FresnelEnabled === value) {
  44401. return;
  44402. }
  44403. StandardMaterial._FresnelEnabled = value;
  44404. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44405. },
  44406. enumerable: true,
  44407. configurable: true
  44408. });
  44409. // Flags used to enable or disable a type of texture for all Standard Materials
  44410. StandardMaterial._DiffuseTextureEnabled = true;
  44411. StandardMaterial._AmbientTextureEnabled = true;
  44412. StandardMaterial._OpacityTextureEnabled = true;
  44413. StandardMaterial._ReflectionTextureEnabled = true;
  44414. StandardMaterial._EmissiveTextureEnabled = true;
  44415. StandardMaterial._SpecularTextureEnabled = true;
  44416. StandardMaterial._BumpTextureEnabled = true;
  44417. StandardMaterial._LightmapTextureEnabled = true;
  44418. StandardMaterial._RefractionTextureEnabled = true;
  44419. StandardMaterial._ColorGradingTextureEnabled = true;
  44420. StandardMaterial._FresnelEnabled = true;
  44421. __decorate([
  44422. BABYLON.serializeAsTexture("diffuseTexture")
  44423. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44424. __decorate([
  44425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44426. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44427. __decorate([
  44428. BABYLON.serializeAsTexture("ambientTexture")
  44429. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44430. __decorate([
  44431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44432. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44433. __decorate([
  44434. BABYLON.serializeAsTexture("opacityTexture")
  44435. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44436. __decorate([
  44437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44438. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44439. __decorate([
  44440. BABYLON.serializeAsTexture("reflectionTexture")
  44441. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44444. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44445. __decorate([
  44446. BABYLON.serializeAsTexture("emissiveTexture")
  44447. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44450. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44451. __decorate([
  44452. BABYLON.serializeAsTexture("specularTexture")
  44453. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44456. ], StandardMaterial.prototype, "specularTexture", void 0);
  44457. __decorate([
  44458. BABYLON.serializeAsTexture("bumpTexture")
  44459. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44462. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44463. __decorate([
  44464. BABYLON.serializeAsTexture("lightmapTexture")
  44465. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44468. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44469. __decorate([
  44470. BABYLON.serializeAsTexture("refractionTexture")
  44471. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44474. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44475. __decorate([
  44476. BABYLON.serializeAsColor3("ambient")
  44477. ], StandardMaterial.prototype, "ambientColor", void 0);
  44478. __decorate([
  44479. BABYLON.serializeAsColor3("diffuse")
  44480. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44481. __decorate([
  44482. BABYLON.serializeAsColor3("specular")
  44483. ], StandardMaterial.prototype, "specularColor", void 0);
  44484. __decorate([
  44485. BABYLON.serializeAsColor3("emissive")
  44486. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44487. __decorate([
  44488. BABYLON.serialize()
  44489. ], StandardMaterial.prototype, "specularPower", void 0);
  44490. __decorate([
  44491. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44492. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44493. __decorate([
  44494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44495. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44496. __decorate([
  44497. BABYLON.serialize("useEmissiveAsIllumination")
  44498. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44499. __decorate([
  44500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44501. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44502. __decorate([
  44503. BABYLON.serialize("linkEmissiveWithDiffuse")
  44504. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44505. __decorate([
  44506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44507. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44508. __decorate([
  44509. BABYLON.serialize("useSpecularOverAlpha")
  44510. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44511. __decorate([
  44512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44513. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44514. __decorate([
  44515. BABYLON.serialize("useReflectionOverAlpha")
  44516. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44517. __decorate([
  44518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44519. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44520. __decorate([
  44521. BABYLON.serialize("disableLighting")
  44522. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44523. __decorate([
  44524. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44525. ], StandardMaterial.prototype, "disableLighting", void 0);
  44526. __decorate([
  44527. BABYLON.serialize("useObjectSpaceNormalMap")
  44528. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44529. __decorate([
  44530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44531. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44532. __decorate([
  44533. BABYLON.serialize("useParallax")
  44534. ], StandardMaterial.prototype, "_useParallax", void 0);
  44535. __decorate([
  44536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44537. ], StandardMaterial.prototype, "useParallax", void 0);
  44538. __decorate([
  44539. BABYLON.serialize("useParallaxOcclusion")
  44540. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44541. __decorate([
  44542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44543. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44544. __decorate([
  44545. BABYLON.serialize()
  44546. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44547. __decorate([
  44548. BABYLON.serialize("roughness")
  44549. ], StandardMaterial.prototype, "_roughness", void 0);
  44550. __decorate([
  44551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44552. ], StandardMaterial.prototype, "roughness", void 0);
  44553. __decorate([
  44554. BABYLON.serialize()
  44555. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44556. __decorate([
  44557. BABYLON.serialize()
  44558. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44559. __decorate([
  44560. BABYLON.serialize()
  44561. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44562. __decorate([
  44563. BABYLON.serialize("useLightmapAsShadowmap")
  44564. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44565. __decorate([
  44566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44567. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44568. __decorate([
  44569. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44570. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44571. __decorate([
  44572. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44573. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44574. __decorate([
  44575. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44576. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44577. __decorate([
  44578. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44579. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44580. __decorate([
  44581. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44582. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44583. __decorate([
  44584. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44585. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44586. __decorate([
  44587. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44588. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44589. __decorate([
  44590. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44591. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44592. __decorate([
  44593. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44594. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44595. __decorate([
  44596. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44597. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44598. __decorate([
  44599. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44600. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44601. __decorate([
  44602. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44603. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44604. __decorate([
  44605. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44606. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44607. __decorate([
  44608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44609. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44610. __decorate([
  44611. BABYLON.serialize("maxSimultaneousLights")
  44612. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44613. __decorate([
  44614. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44615. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44616. __decorate([
  44617. BABYLON.serialize("invertNormalMapX")
  44618. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44619. __decorate([
  44620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44621. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44622. __decorate([
  44623. BABYLON.serialize("invertNormalMapY")
  44624. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44625. __decorate([
  44626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44627. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44628. __decorate([
  44629. BABYLON.serialize("twoSidedLighting")
  44630. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44631. __decorate([
  44632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44633. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44634. __decorate([
  44635. BABYLON.serialize()
  44636. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44637. return StandardMaterial;
  44638. }(BABYLON.PushMaterial));
  44639. BABYLON.StandardMaterial = StandardMaterial;
  44640. })(BABYLON || (BABYLON = {}));
  44641. //# sourceMappingURL=babylon.standardMaterial.js.map
  44642. var BABYLON;
  44643. (function (BABYLON) {
  44644. /**
  44645. * Manages the defines for the PBR Material.
  44646. * @hiddenChildren
  44647. */
  44648. var PBRMaterialDefines = /** @class */ (function (_super) {
  44649. __extends(PBRMaterialDefines, _super);
  44650. /**
  44651. * Initializes the PBR Material defines.
  44652. */
  44653. function PBRMaterialDefines() {
  44654. var _this = _super.call(this) || this;
  44655. _this.PBR = true;
  44656. _this.MAINUV1 = false;
  44657. _this.MAINUV2 = false;
  44658. _this.UV1 = false;
  44659. _this.UV2 = false;
  44660. _this.ALBEDO = false;
  44661. _this.ALBEDODIRECTUV = 0;
  44662. _this.VERTEXCOLOR = false;
  44663. _this.AMBIENT = false;
  44664. _this.AMBIENTDIRECTUV = 0;
  44665. _this.AMBIENTINGRAYSCALE = false;
  44666. _this.OPACITY = false;
  44667. _this.VERTEXALPHA = false;
  44668. _this.OPACITYDIRECTUV = 0;
  44669. _this.OPACITYRGB = false;
  44670. _this.ALPHATEST = false;
  44671. _this.DEPTHPREPASS = false;
  44672. _this.ALPHABLEND = false;
  44673. _this.ALPHAFROMALBEDO = false;
  44674. _this.ALPHATESTVALUE = "0.5";
  44675. _this.SPECULAROVERALPHA = false;
  44676. _this.RADIANCEOVERALPHA = false;
  44677. _this.ALPHAFRESNEL = false;
  44678. _this.LINEARALPHAFRESNEL = false;
  44679. _this.PREMULTIPLYALPHA = false;
  44680. _this.EMISSIVE = false;
  44681. _this.EMISSIVEDIRECTUV = 0;
  44682. _this.REFLECTIVITY = false;
  44683. _this.REFLECTIVITYDIRECTUV = 0;
  44684. _this.SPECULARTERM = false;
  44685. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44686. _this.MICROSURFACEAUTOMATIC = false;
  44687. _this.LODBASEDMICROSFURACE = false;
  44688. _this.MICROSURFACEMAP = false;
  44689. _this.MICROSURFACEMAPDIRECTUV = 0;
  44690. _this.METALLICWORKFLOW = false;
  44691. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44692. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44693. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44694. _this.AOSTOREINMETALMAPRED = false;
  44695. _this.ENVIRONMENTBRDF = false;
  44696. _this.NORMAL = false;
  44697. _this.TANGENT = false;
  44698. _this.BUMP = false;
  44699. _this.BUMPDIRECTUV = 0;
  44700. _this.OBJECTSPACE_NORMALMAP = false;
  44701. _this.PARALLAX = false;
  44702. _this.PARALLAXOCCLUSION = false;
  44703. _this.NORMALXYSCALE = true;
  44704. _this.LIGHTMAP = false;
  44705. _this.LIGHTMAPDIRECTUV = 0;
  44706. _this.USELIGHTMAPASSHADOWMAP = false;
  44707. _this.GAMMALIGHTMAP = false;
  44708. _this.REFLECTION = false;
  44709. _this.REFLECTIONMAP_3D = false;
  44710. _this.REFLECTIONMAP_SPHERICAL = false;
  44711. _this.REFLECTIONMAP_PLANAR = false;
  44712. _this.REFLECTIONMAP_CUBIC = false;
  44713. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44714. _this.REFLECTIONMAP_PROJECTION = false;
  44715. _this.REFLECTIONMAP_SKYBOX = false;
  44716. _this.REFLECTIONMAP_EXPLICIT = false;
  44717. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44718. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44719. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44720. _this.INVERTCUBICMAP = false;
  44721. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44722. _this.USESPHERICALINVERTEX = false;
  44723. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44724. _this.LODINREFLECTIONALPHA = false;
  44725. _this.GAMMAREFLECTION = false;
  44726. _this.RGBDREFLECTION = false;
  44727. _this.RADIANCEOCCLUSION = false;
  44728. _this.HORIZONOCCLUSION = false;
  44729. _this.REFRACTION = false;
  44730. _this.REFRACTIONMAP_3D = false;
  44731. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44732. _this.LODINREFRACTIONALPHA = false;
  44733. _this.GAMMAREFRACTION = false;
  44734. _this.RGBDREFRACTION = false;
  44735. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44736. _this.INSTANCES = false;
  44737. _this.NUM_BONE_INFLUENCERS = 0;
  44738. _this.BonesPerMesh = 0;
  44739. _this.NONUNIFORMSCALING = false;
  44740. _this.MORPHTARGETS = false;
  44741. _this.MORPHTARGETS_NORMAL = false;
  44742. _this.MORPHTARGETS_TANGENT = false;
  44743. _this.NUM_MORPH_INFLUENCERS = 0;
  44744. _this.IMAGEPROCESSING = false;
  44745. _this.VIGNETTE = false;
  44746. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44747. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44748. _this.TONEMAPPING = false;
  44749. _this.CONTRAST = false;
  44750. _this.COLORCURVES = false;
  44751. _this.COLORGRADING = false;
  44752. _this.COLORGRADING3D = false;
  44753. _this.SAMPLER3DGREENDEPTH = false;
  44754. _this.SAMPLER3DBGRMAP = false;
  44755. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44756. _this.EXPOSURE = false;
  44757. _this.USEPHYSICALLIGHTFALLOFF = false;
  44758. _this.TWOSIDEDLIGHTING = false;
  44759. _this.SHADOWFLOAT = false;
  44760. _this.CLIPPLANE = false;
  44761. _this.POINTSIZE = false;
  44762. _this.FOG = false;
  44763. _this.LOGARITHMICDEPTH = false;
  44764. _this.FORCENORMALFORWARD = false;
  44765. _this.SPECULARAA = false;
  44766. _this.UNLIT = false;
  44767. _this.rebuild();
  44768. return _this;
  44769. }
  44770. /**
  44771. * Resets the PBR Material defines.
  44772. */
  44773. PBRMaterialDefines.prototype.reset = function () {
  44774. _super.prototype.reset.call(this);
  44775. this.ALPHATESTVALUE = "0.5";
  44776. this.PBR = true;
  44777. };
  44778. return PBRMaterialDefines;
  44779. }(BABYLON.MaterialDefines));
  44780. /**
  44781. * The Physically based material base class of BJS.
  44782. *
  44783. * This offers the main features of a standard PBR material.
  44784. * For more information, please refer to the documentation :
  44785. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44786. */
  44787. var PBRBaseMaterial = /** @class */ (function (_super) {
  44788. __extends(PBRBaseMaterial, _super);
  44789. /**
  44790. * Instantiates a new PBRMaterial instance.
  44791. *
  44792. * @param name The material name
  44793. * @param scene The scene the material will be use in.
  44794. */
  44795. function PBRBaseMaterial(name, scene) {
  44796. var _this = _super.call(this, name, scene) || this;
  44797. /**
  44798. * Intensity of the direct lights e.g. the four lights available in your scene.
  44799. * This impacts both the direct diffuse and specular highlights.
  44800. */
  44801. _this._directIntensity = 1.0;
  44802. /**
  44803. * Intensity of the emissive part of the material.
  44804. * This helps controlling the emissive effect without modifying the emissive color.
  44805. */
  44806. _this._emissiveIntensity = 1.0;
  44807. /**
  44808. * Intensity of the environment e.g. how much the environment will light the object
  44809. * either through harmonics for rough material or through the refelction for shiny ones.
  44810. */
  44811. _this._environmentIntensity = 1.0;
  44812. /**
  44813. * This is a special control allowing the reduction of the specular highlights coming from the
  44814. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44815. */
  44816. _this._specularIntensity = 1.0;
  44817. /**
  44818. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44819. */
  44820. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44821. /**
  44822. * Debug Control allowing disabling the bump map on this material.
  44823. */
  44824. _this._disableBumpMap = false;
  44825. /**
  44826. * AKA Occlusion Texture Intensity in other nomenclature.
  44827. */
  44828. _this._ambientTextureStrength = 1.0;
  44829. /**
  44830. * The color of a material in ambient lighting.
  44831. */
  44832. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44833. /**
  44834. * AKA Diffuse Color in other nomenclature.
  44835. */
  44836. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44837. /**
  44838. * AKA Specular Color in other nomenclature.
  44839. */
  44840. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44841. /**
  44842. * The color applied when light is reflected from a material.
  44843. */
  44844. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44845. /**
  44846. * The color applied when light is emitted from a material.
  44847. */
  44848. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44849. /**
  44850. * AKA Glossiness in other nomenclature.
  44851. */
  44852. _this._microSurface = 0.9;
  44853. /**
  44854. * source material index of refraction (IOR)' / 'destination material IOR.
  44855. */
  44856. _this._indexOfRefraction = 0.66;
  44857. /**
  44858. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44859. */
  44860. _this._invertRefractionY = false;
  44861. /**
  44862. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44863. * Materials half opaque for instance using refraction could benefit from this control.
  44864. */
  44865. _this._linkRefractionWithTransparency = false;
  44866. /**
  44867. * Specifies that the material will use the light map as a show map.
  44868. */
  44869. _this._useLightmapAsShadowmap = false;
  44870. /**
  44871. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44872. * makes the reflect vector face the model (under horizon).
  44873. */
  44874. _this._useHorizonOcclusion = true;
  44875. /**
  44876. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44877. * too much the area relying on ambient texture to define their ambient occlusion.
  44878. */
  44879. _this._useRadianceOcclusion = true;
  44880. /**
  44881. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44882. */
  44883. _this._useAlphaFromAlbedoTexture = false;
  44884. /**
  44885. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44886. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44887. */
  44888. _this._useSpecularOverAlpha = true;
  44889. /**
  44890. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44891. */
  44892. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44893. /**
  44894. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44895. */
  44896. _this._useRoughnessFromMetallicTextureAlpha = true;
  44897. /**
  44898. * Specifies if the metallic texture contains the roughness information in its green channel.
  44899. */
  44900. _this._useRoughnessFromMetallicTextureGreen = false;
  44901. /**
  44902. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44903. */
  44904. _this._useMetallnessFromMetallicTextureBlue = false;
  44905. /**
  44906. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44907. */
  44908. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44909. /**
  44910. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44911. */
  44912. _this._useAmbientInGrayScale = false;
  44913. /**
  44914. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44915. * The material will try to infer what glossiness each pixel should be.
  44916. */
  44917. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44918. /**
  44919. * BJS is using an harcoded light falloff based on a manually sets up range.
  44920. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44921. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44922. */
  44923. _this._usePhysicalLightFalloff = true;
  44924. /**
  44925. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44926. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44927. */
  44928. _this._useRadianceOverAlpha = true;
  44929. /**
  44930. * Allows using an object space normal map (instead of tangent space).
  44931. */
  44932. _this._useObjectSpaceNormalMap = false;
  44933. /**
  44934. * Allows using the bump map in parallax mode.
  44935. */
  44936. _this._useParallax = false;
  44937. /**
  44938. * Allows using the bump map in parallax occlusion mode.
  44939. */
  44940. _this._useParallaxOcclusion = false;
  44941. /**
  44942. * Controls the scale bias of the parallax mode.
  44943. */
  44944. _this._parallaxScaleBias = 0.05;
  44945. /**
  44946. * If sets to true, disables all the lights affecting the material.
  44947. */
  44948. _this._disableLighting = false;
  44949. /**
  44950. * Number of Simultaneous lights allowed on the material.
  44951. */
  44952. _this._maxSimultaneousLights = 4;
  44953. /**
  44954. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44955. */
  44956. _this._invertNormalMapX = false;
  44957. /**
  44958. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44959. */
  44960. _this._invertNormalMapY = false;
  44961. /**
  44962. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44963. */
  44964. _this._twoSidedLighting = false;
  44965. /**
  44966. * Defines the alpha limits in alpha test mode.
  44967. */
  44968. _this._alphaCutOff = 0.4;
  44969. /**
  44970. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44971. */
  44972. _this._forceAlphaTest = false;
  44973. /**
  44974. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44975. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44976. */
  44977. _this._useAlphaFresnel = false;
  44978. /**
  44979. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44980. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44981. */
  44982. _this._useLinearAlphaFresnel = false;
  44983. /**
  44984. * The transparency mode of the material.
  44985. */
  44986. _this._transparencyMode = null;
  44987. /**
  44988. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44989. * from cos thetav and roughness:
  44990. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44991. */
  44992. _this._environmentBRDFTexture = null;
  44993. /**
  44994. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44995. */
  44996. _this._forceIrradianceInFragment = false;
  44997. /**
  44998. * Force normal to face away from face.
  44999. */
  45000. _this._forceNormalForward = false;
  45001. /**
  45002. * Enables specular anti aliasing in the PBR shader.
  45003. * It will both interacts on the Geometry for analytical and IBL lighting.
  45004. * It also prefilter the roughness map based on the bump values.
  45005. */
  45006. _this._enableSpecularAntiAliasing = false;
  45007. /**
  45008. * Stores the available render targets.
  45009. */
  45010. _this._renderTargets = new BABYLON.SmartArray(16);
  45011. /**
  45012. * Sets the global ambient color for the material used in lighting calculations.
  45013. */
  45014. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45015. /**
  45016. * If set to true, no lighting calculations will be applied.
  45017. */
  45018. _this._unlit = false;
  45019. // Setup the default processing configuration to the scene.
  45020. _this._attachImageProcessingConfiguration(null);
  45021. _this.getRenderTargetTextures = function () {
  45022. _this._renderTargets.reset();
  45023. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45024. _this._renderTargets.push(_this._reflectionTexture);
  45025. }
  45026. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45027. _this._renderTargets.push(_this._refractionTexture);
  45028. }
  45029. return _this._renderTargets;
  45030. };
  45031. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45032. return _this;
  45033. }
  45034. /**
  45035. * Attaches a new image processing configuration to the PBR Material.
  45036. * @param configuration
  45037. */
  45038. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45039. var _this = this;
  45040. if (configuration === this._imageProcessingConfiguration) {
  45041. return;
  45042. }
  45043. // Detaches observer.
  45044. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45045. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45046. }
  45047. // Pick the scene configuration if needed.
  45048. if (!configuration) {
  45049. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45050. }
  45051. else {
  45052. this._imageProcessingConfiguration = configuration;
  45053. }
  45054. // Attaches observer.
  45055. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45056. _this._markAllSubMeshesAsImageProcessingDirty();
  45057. });
  45058. };
  45059. /**
  45060. * Gets the name of the material class.
  45061. */
  45062. PBRBaseMaterial.prototype.getClassName = function () {
  45063. return "PBRBaseMaterial";
  45064. };
  45065. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45066. /**
  45067. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45068. */
  45069. get: function () {
  45070. return this._useLogarithmicDepth;
  45071. },
  45072. /**
  45073. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45074. */
  45075. set: function (value) {
  45076. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45077. },
  45078. enumerable: true,
  45079. configurable: true
  45080. });
  45081. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45082. /**
  45083. * Gets the current transparency mode.
  45084. */
  45085. get: function () {
  45086. return this._transparencyMode;
  45087. },
  45088. /**
  45089. * Sets the transparency mode of the material.
  45090. *
  45091. * | Value | Type | Description |
  45092. * | ----- | ----------------------------------- | ----------- |
  45093. * | 0 | OPAQUE | |
  45094. * | 1 | ALPHATEST | |
  45095. * | 2 | ALPHABLEND | |
  45096. * | 3 | ALPHATESTANDBLEND | |
  45097. *
  45098. */
  45099. set: function (value) {
  45100. if (this._transparencyMode === value) {
  45101. return;
  45102. }
  45103. this._transparencyMode = value;
  45104. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45105. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45106. },
  45107. enumerable: true,
  45108. configurable: true
  45109. });
  45110. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45111. /**
  45112. * Returns true if alpha blending should be disabled.
  45113. */
  45114. get: function () {
  45115. return (this._linkRefractionWithTransparency ||
  45116. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45117. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45118. },
  45119. enumerable: true,
  45120. configurable: true
  45121. });
  45122. /**
  45123. * Specifies whether or not this material should be rendered in alpha blend mode.
  45124. */
  45125. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45126. if (this._disableAlphaBlending) {
  45127. return false;
  45128. }
  45129. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45130. };
  45131. /**
  45132. * Specifies if the mesh will require alpha blending.
  45133. * @param mesh - BJS mesh.
  45134. */
  45135. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45136. if (this._disableAlphaBlending) {
  45137. return false;
  45138. }
  45139. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45140. };
  45141. /**
  45142. * Specifies whether or not this material should be rendered in alpha test mode.
  45143. */
  45144. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45145. if (this._forceAlphaTest) {
  45146. return true;
  45147. }
  45148. if (this._linkRefractionWithTransparency) {
  45149. return false;
  45150. }
  45151. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45152. };
  45153. /**
  45154. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45155. */
  45156. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45157. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45158. };
  45159. /**
  45160. * Gets the texture used for the alpha test.
  45161. */
  45162. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45163. return this._albedoTexture;
  45164. };
  45165. /**
  45166. * Specifies that the submesh is ready to be used.
  45167. * @param mesh - BJS mesh.
  45168. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45169. * @param useInstances - Specifies that instances should be used.
  45170. * @returns - boolean indicating that the submesh is ready or not.
  45171. */
  45172. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45173. if (subMesh.effect && this.isFrozen) {
  45174. if (this._wasPreviouslyReady) {
  45175. return true;
  45176. }
  45177. }
  45178. if (!subMesh._materialDefines) {
  45179. subMesh._materialDefines = new PBRMaterialDefines();
  45180. }
  45181. var defines = subMesh._materialDefines;
  45182. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45183. if (defines._renderId === this.getScene().getRenderId()) {
  45184. return true;
  45185. }
  45186. }
  45187. var scene = this.getScene();
  45188. var engine = scene.getEngine();
  45189. if (defines._areTexturesDirty) {
  45190. if (scene.texturesEnabled) {
  45191. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45192. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45193. return false;
  45194. }
  45195. }
  45196. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45197. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45198. return false;
  45199. }
  45200. }
  45201. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45202. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45203. return false;
  45204. }
  45205. }
  45206. var reflectionTexture = this._getReflectionTexture();
  45207. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45208. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45209. return false;
  45210. }
  45211. }
  45212. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45213. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45214. return false;
  45215. }
  45216. }
  45217. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45218. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45219. return false;
  45220. }
  45221. }
  45222. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45223. if (this._metallicTexture) {
  45224. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45225. return false;
  45226. }
  45227. }
  45228. else if (this._reflectivityTexture) {
  45229. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45230. return false;
  45231. }
  45232. }
  45233. if (this._microSurfaceTexture) {
  45234. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45235. return false;
  45236. }
  45237. }
  45238. }
  45239. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45240. // Bump texture cannot be not blocking.
  45241. if (!this._bumpTexture.isReady()) {
  45242. return false;
  45243. }
  45244. }
  45245. var refractionTexture = this._getRefractionTexture();
  45246. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45247. if (!refractionTexture.isReadyOrNotBlocking()) {
  45248. return false;
  45249. }
  45250. }
  45251. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45252. // This is blocking.
  45253. if (!this._environmentBRDFTexture.isReady()) {
  45254. return false;
  45255. }
  45256. }
  45257. }
  45258. }
  45259. if (defines._areImageProcessingDirty) {
  45260. if (!this._imageProcessingConfiguration.isReady()) {
  45261. return false;
  45262. }
  45263. }
  45264. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45265. mesh.createNormals(true);
  45266. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45267. }
  45268. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45269. if (effect) {
  45270. scene.resetCachedMaterial();
  45271. subMesh.setEffect(effect, defines);
  45272. this.buildUniformLayout();
  45273. }
  45274. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45275. return false;
  45276. }
  45277. defines._renderId = scene.getRenderId();
  45278. this._wasPreviouslyReady = true;
  45279. return true;
  45280. };
  45281. /**
  45282. * Specifies if the material uses metallic roughness workflow.
  45283. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45284. */
  45285. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45286. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45287. return true;
  45288. }
  45289. return false;
  45290. };
  45291. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45292. if (onCompiled === void 0) { onCompiled = null; }
  45293. if (onError === void 0) { onError = null; }
  45294. if (useInstances === void 0) { useInstances = null; }
  45295. if (useClipPlane === void 0) { useClipPlane = null; }
  45296. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45297. if (!defines.isDirty) {
  45298. return null;
  45299. }
  45300. defines.markAsProcessed();
  45301. var scene = this.getScene();
  45302. var engine = scene.getEngine();
  45303. // Fallbacks
  45304. var fallbacks = new BABYLON.EffectFallbacks();
  45305. var fallbackRank = 0;
  45306. if (defines.USESPHERICALINVERTEX) {
  45307. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45308. }
  45309. if (defines.FOG) {
  45310. fallbacks.addFallback(fallbackRank, "FOG");
  45311. }
  45312. if (defines.SPECULARAA) {
  45313. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45314. }
  45315. if (defines.POINTSIZE) {
  45316. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45317. }
  45318. if (defines.LOGARITHMICDEPTH) {
  45319. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45320. }
  45321. if (defines.PARALLAX) {
  45322. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45323. }
  45324. if (defines.PARALLAXOCCLUSION) {
  45325. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45326. }
  45327. if (defines.ENVIRONMENTBRDF) {
  45328. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45329. }
  45330. if (defines.TANGENT) {
  45331. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45332. }
  45333. if (defines.BUMP) {
  45334. fallbacks.addFallback(fallbackRank++, "BUMP");
  45335. }
  45336. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45337. if (defines.SPECULARTERM) {
  45338. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45339. }
  45340. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45341. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45342. }
  45343. if (defines.LIGHTMAP) {
  45344. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45345. }
  45346. if (defines.NORMAL) {
  45347. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45348. }
  45349. if (defines.AMBIENT) {
  45350. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45351. }
  45352. if (defines.EMISSIVE) {
  45353. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45354. }
  45355. if (defines.VERTEXCOLOR) {
  45356. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45357. }
  45358. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45359. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45360. }
  45361. if (defines.MORPHTARGETS) {
  45362. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45363. }
  45364. //Attributes
  45365. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45366. if (defines.NORMAL) {
  45367. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45368. }
  45369. if (defines.TANGENT) {
  45370. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45371. }
  45372. if (defines.UV1) {
  45373. attribs.push(BABYLON.VertexBuffer.UVKind);
  45374. }
  45375. if (defines.UV2) {
  45376. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45377. }
  45378. if (defines.VERTEXCOLOR) {
  45379. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45380. }
  45381. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45382. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45383. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45384. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45385. "vFogInfos", "vFogColor", "pointSize",
  45386. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45387. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45388. "mBones",
  45389. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45390. "vLightingIntensity",
  45391. "logarithmicDepthConstant",
  45392. "vSphericalX", "vSphericalY", "vSphericalZ",
  45393. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45394. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45395. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45396. "vTangentSpaceParams"
  45397. ];
  45398. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45399. "bumpSampler", "lightmapSampler", "opacitySampler",
  45400. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45401. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45402. "microSurfaceSampler", "environmentBrdfSampler"];
  45403. var uniformBuffers = ["Material", "Scene"];
  45404. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45405. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45406. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45407. uniformsNames: uniforms,
  45408. uniformBuffersNames: uniformBuffers,
  45409. samplers: samplers,
  45410. defines: defines,
  45411. maxSimultaneousLights: this._maxSimultaneousLights
  45412. });
  45413. var join = defines.toString();
  45414. return engine.createEffect("pbr", {
  45415. attributes: attribs,
  45416. uniformsNames: uniforms,
  45417. uniformBuffersNames: uniformBuffers,
  45418. samplers: samplers,
  45419. defines: join,
  45420. fallbacks: fallbacks,
  45421. onCompiled: onCompiled,
  45422. onError: onError,
  45423. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45424. }, engine);
  45425. };
  45426. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45427. if (useInstances === void 0) { useInstances = null; }
  45428. if (useClipPlane === void 0) { useClipPlane = null; }
  45429. var scene = this.getScene();
  45430. var engine = scene.getEngine();
  45431. // Lights
  45432. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45433. defines._needNormals = true;
  45434. // Textures
  45435. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45436. if (defines._areTexturesDirty) {
  45437. defines._needUVs = false;
  45438. if (scene.texturesEnabled) {
  45439. if (scene.getEngine().getCaps().textureLOD) {
  45440. defines.LODBASEDMICROSFURACE = true;
  45441. }
  45442. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45443. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45444. }
  45445. else {
  45446. defines.ALBEDO = false;
  45447. }
  45448. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45449. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45450. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45451. }
  45452. else {
  45453. defines.AMBIENT = false;
  45454. }
  45455. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45457. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45458. }
  45459. else {
  45460. defines.OPACITY = false;
  45461. }
  45462. var reflectionTexture = this._getReflectionTexture();
  45463. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45464. defines.REFLECTION = true;
  45465. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45466. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45467. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45468. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45469. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45470. defines.INVERTCUBICMAP = true;
  45471. }
  45472. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45473. switch (reflectionTexture.coordinatesMode) {
  45474. case BABYLON.Texture.EXPLICIT_MODE:
  45475. defines.REFLECTIONMAP_EXPLICIT = true;
  45476. break;
  45477. case BABYLON.Texture.PLANAR_MODE:
  45478. defines.REFLECTIONMAP_PLANAR = true;
  45479. break;
  45480. case BABYLON.Texture.PROJECTION_MODE:
  45481. defines.REFLECTIONMAP_PROJECTION = true;
  45482. break;
  45483. case BABYLON.Texture.SKYBOX_MODE:
  45484. defines.REFLECTIONMAP_SKYBOX = true;
  45485. break;
  45486. case BABYLON.Texture.SPHERICAL_MODE:
  45487. defines.REFLECTIONMAP_SPHERICAL = true;
  45488. break;
  45489. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45490. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45491. break;
  45492. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45493. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45494. break;
  45495. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45496. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45497. break;
  45498. case BABYLON.Texture.CUBIC_MODE:
  45499. case BABYLON.Texture.INVCUBIC_MODE:
  45500. default:
  45501. defines.REFLECTIONMAP_CUBIC = true;
  45502. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45503. break;
  45504. }
  45505. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45506. if (reflectionTexture.sphericalPolynomial) {
  45507. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45508. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45509. defines.USESPHERICALINVERTEX = false;
  45510. }
  45511. else {
  45512. defines.USESPHERICALINVERTEX = true;
  45513. }
  45514. }
  45515. }
  45516. }
  45517. else {
  45518. defines.REFLECTION = false;
  45519. defines.REFLECTIONMAP_3D = false;
  45520. defines.REFLECTIONMAP_SPHERICAL = false;
  45521. defines.REFLECTIONMAP_PLANAR = false;
  45522. defines.REFLECTIONMAP_CUBIC = false;
  45523. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45524. defines.REFLECTIONMAP_PROJECTION = false;
  45525. defines.REFLECTIONMAP_SKYBOX = false;
  45526. defines.REFLECTIONMAP_EXPLICIT = false;
  45527. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45528. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45529. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45530. defines.INVERTCUBICMAP = false;
  45531. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45532. defines.USESPHERICALINVERTEX = false;
  45533. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45534. defines.LODINREFLECTIONALPHA = false;
  45535. defines.GAMMAREFLECTION = false;
  45536. defines.RGBDREFLECTION = false;
  45537. }
  45538. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45539. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45540. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45541. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45542. }
  45543. else {
  45544. defines.LIGHTMAP = false;
  45545. }
  45546. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45547. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45548. }
  45549. else {
  45550. defines.EMISSIVE = false;
  45551. }
  45552. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45553. if (this._metallicTexture) {
  45554. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45555. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45556. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45557. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45558. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45559. }
  45560. else if (this._reflectivityTexture) {
  45561. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45562. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45563. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45564. }
  45565. else {
  45566. defines.REFLECTIVITY = false;
  45567. }
  45568. if (this._microSurfaceTexture) {
  45569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45570. }
  45571. else {
  45572. defines.MICROSURFACEMAP = false;
  45573. }
  45574. }
  45575. else {
  45576. defines.REFLECTIVITY = false;
  45577. defines.MICROSURFACEMAP = false;
  45578. }
  45579. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45580. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45581. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45582. defines.PARALLAX = true;
  45583. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45584. }
  45585. else {
  45586. defines.PARALLAX = false;
  45587. }
  45588. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45589. }
  45590. else {
  45591. defines.BUMP = false;
  45592. }
  45593. var refractionTexture = this._getRefractionTexture();
  45594. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45595. defines.REFRACTION = true;
  45596. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45597. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45598. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45599. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45600. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45601. if (this._linkRefractionWithTransparency) {
  45602. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45603. }
  45604. }
  45605. else {
  45606. defines.REFRACTION = false;
  45607. }
  45608. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45609. defines.ENVIRONMENTBRDF = true;
  45610. }
  45611. else {
  45612. defines.ENVIRONMENTBRDF = false;
  45613. }
  45614. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45615. defines.ALPHAFROMALBEDO = true;
  45616. }
  45617. else {
  45618. defines.ALPHAFROMALBEDO = false;
  45619. }
  45620. }
  45621. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45622. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45623. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45624. if (!this.backFaceCulling && this._twoSidedLighting) {
  45625. defines.TWOSIDEDLIGHTING = true;
  45626. }
  45627. else {
  45628. defines.TWOSIDEDLIGHTING = false;
  45629. }
  45630. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45631. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45632. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45633. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45634. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45635. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45636. }
  45637. if (defines._areImageProcessingDirty) {
  45638. this._imageProcessingConfiguration.prepareDefines(defines);
  45639. }
  45640. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45641. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45642. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45643. // Misc.
  45644. if (defines._areMiscDirty) {
  45645. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45646. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45647. }
  45648. // Values that need to be evaluated on every frame
  45649. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45650. // Attribs
  45651. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45652. };
  45653. /**
  45654. * Force shader compilation
  45655. */
  45656. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45657. var _this = this;
  45658. var localOptions = __assign({ clipPlane: false }, options);
  45659. var defines = new PBRMaterialDefines();
  45660. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45661. if (effect.isReady()) {
  45662. if (onCompiled) {
  45663. onCompiled(this);
  45664. }
  45665. }
  45666. else {
  45667. effect.onCompileObservable.add(function () {
  45668. if (onCompiled) {
  45669. onCompiled(_this);
  45670. }
  45671. });
  45672. }
  45673. };
  45674. /**
  45675. * Initializes the uniform buffer layout for the shader.
  45676. */
  45677. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45678. // Order is important !
  45679. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45680. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45681. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45682. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45683. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45684. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45685. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45686. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45687. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45688. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45689. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45690. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45691. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45692. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45693. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45694. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45695. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45696. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45697. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45698. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45699. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45700. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45701. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45702. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45703. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45704. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45705. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45706. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45707. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45708. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45709. this._uniformBuffer.addUniform("pointSize", 1);
  45710. this._uniformBuffer.create();
  45711. };
  45712. /**
  45713. * Unbinds the textures.
  45714. */
  45715. PBRBaseMaterial.prototype.unbind = function () {
  45716. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45717. this._uniformBuffer.setTexture("reflectionSampler", null);
  45718. }
  45719. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45720. this._uniformBuffer.setTexture("refractionSampler", null);
  45721. }
  45722. _super.prototype.unbind.call(this);
  45723. };
  45724. /**
  45725. * Binds the submesh data.
  45726. * @param world - The world matrix.
  45727. * @param mesh - The BJS mesh.
  45728. * @param subMesh - A submesh of the BJS mesh.
  45729. */
  45730. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45731. var scene = this.getScene();
  45732. var defines = subMesh._materialDefines;
  45733. if (!defines) {
  45734. return;
  45735. }
  45736. var effect = subMesh.effect;
  45737. if (!effect) {
  45738. return;
  45739. }
  45740. this._activeEffect = effect;
  45741. // Matrices
  45742. this.bindOnlyWorldMatrix(world);
  45743. // Normal Matrix
  45744. if (defines.OBJECTSPACE_NORMALMAP) {
  45745. world.toNormalMatrix(this._normalMatrix);
  45746. this.bindOnlyNormalMatrix(this._normalMatrix);
  45747. }
  45748. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45749. // Bones
  45750. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45751. var reflectionTexture = null;
  45752. if (mustRebind) {
  45753. this._uniformBuffer.bindToEffect(effect, "Material");
  45754. this.bindViewProjection(effect);
  45755. reflectionTexture = this._getReflectionTexture();
  45756. var refractionTexture = this._getRefractionTexture();
  45757. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45758. // Texture uniforms
  45759. if (scene.texturesEnabled) {
  45760. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45761. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45762. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45763. }
  45764. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45765. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45766. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45767. }
  45768. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45769. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45770. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45771. }
  45772. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45773. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45774. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45775. if (reflectionTexture.boundingBoxSize) {
  45776. var cubeTexture = reflectionTexture;
  45777. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45778. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45779. }
  45780. var polynomials = reflectionTexture.sphericalPolynomial;
  45781. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45782. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45783. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45784. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45785. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45786. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45787. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45788. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45789. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45790. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45791. }
  45792. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45793. }
  45794. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45795. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45796. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45797. }
  45798. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45799. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45800. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45801. }
  45802. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45803. if (this._metallicTexture) {
  45804. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45805. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45806. }
  45807. else if (this._reflectivityTexture) {
  45808. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45809. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45810. }
  45811. if (this._microSurfaceTexture) {
  45812. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45813. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45814. }
  45815. }
  45816. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45817. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45818. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45819. if (scene._mirroredCameraPosition) {
  45820. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45821. }
  45822. else {
  45823. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45824. }
  45825. }
  45826. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45827. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45828. var depth = 1.0;
  45829. if (!refractionTexture.isCube) {
  45830. if (refractionTexture.depth) {
  45831. depth = refractionTexture.depth;
  45832. }
  45833. }
  45834. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45835. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45836. }
  45837. }
  45838. // Point size
  45839. if (this.pointsCloud) {
  45840. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45841. }
  45842. // Colors
  45843. if (defines.METALLICWORKFLOW) {
  45844. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45845. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45846. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45847. }
  45848. else {
  45849. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45850. }
  45851. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45852. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45853. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45854. // Misc
  45855. this._lightingInfos.x = this._directIntensity;
  45856. this._lightingInfos.y = this._emissiveIntensity;
  45857. this._lightingInfos.z = this._environmentIntensity;
  45858. this._lightingInfos.w = this._specularIntensity;
  45859. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45860. }
  45861. // Textures
  45862. if (scene.texturesEnabled) {
  45863. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45864. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45865. }
  45866. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45867. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45868. }
  45869. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45870. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45871. }
  45872. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45873. if (defines.LODBASEDMICROSFURACE) {
  45874. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45875. }
  45876. else {
  45877. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45878. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45879. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45880. }
  45881. }
  45882. if (defines.ENVIRONMENTBRDF) {
  45883. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45884. }
  45885. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45886. if (defines.LODBASEDMICROSFURACE) {
  45887. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45888. }
  45889. else {
  45890. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45891. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45892. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45893. }
  45894. }
  45895. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45896. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45897. }
  45898. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45899. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45900. }
  45901. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45902. if (this._metallicTexture) {
  45903. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45904. }
  45905. else if (this._reflectivityTexture) {
  45906. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45907. }
  45908. if (this._microSurfaceTexture) {
  45909. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45910. }
  45911. }
  45912. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45913. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45914. }
  45915. }
  45916. // Clip plane
  45917. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45918. // Colors
  45919. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45920. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45921. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45922. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45923. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45924. }
  45925. if (mustRebind || !this.isFrozen) {
  45926. // Lights
  45927. if (scene.lightsEnabled && !this._disableLighting) {
  45928. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45929. }
  45930. // View
  45931. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45932. this.bindView(effect);
  45933. }
  45934. // Fog
  45935. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45936. // Morph targets
  45937. if (defines.NUM_MORPH_INFLUENCERS) {
  45938. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45939. }
  45940. // image processing
  45941. this._imageProcessingConfiguration.bind(this._activeEffect);
  45942. // Log. depth
  45943. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45944. }
  45945. this._uniformBuffer.update();
  45946. this._afterBind(mesh, this._activeEffect);
  45947. };
  45948. /**
  45949. * Returns the animatable textures.
  45950. * @returns - Array of animatable textures.
  45951. */
  45952. PBRBaseMaterial.prototype.getAnimatables = function () {
  45953. var results = [];
  45954. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45955. results.push(this._albedoTexture);
  45956. }
  45957. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45958. results.push(this._ambientTexture);
  45959. }
  45960. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45961. results.push(this._opacityTexture);
  45962. }
  45963. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45964. results.push(this._reflectionTexture);
  45965. }
  45966. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45967. results.push(this._emissiveTexture);
  45968. }
  45969. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45970. results.push(this._metallicTexture);
  45971. }
  45972. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45973. results.push(this._reflectivityTexture);
  45974. }
  45975. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45976. results.push(this._bumpTexture);
  45977. }
  45978. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45979. results.push(this._lightmapTexture);
  45980. }
  45981. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45982. results.push(this._refractionTexture);
  45983. }
  45984. return results;
  45985. };
  45986. /**
  45987. * Returns the texture used for reflections.
  45988. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45989. */
  45990. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45991. if (this._reflectionTexture) {
  45992. return this._reflectionTexture;
  45993. }
  45994. return this.getScene().environmentTexture;
  45995. };
  45996. /**
  45997. * Returns the texture used for refraction or null if none is used.
  45998. * @returns - Refection texture if present. If no refraction texture and refraction
  45999. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46000. */
  46001. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46002. if (this._refractionTexture) {
  46003. return this._refractionTexture;
  46004. }
  46005. if (this._linkRefractionWithTransparency) {
  46006. return this.getScene().environmentTexture;
  46007. }
  46008. return null;
  46009. };
  46010. /**
  46011. * Disposes the resources of the material.
  46012. * @param forceDisposeEffect - Forces the disposal of effects.
  46013. * @param forceDisposeTextures - Forces the disposal of all textures.
  46014. */
  46015. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46016. if (forceDisposeTextures) {
  46017. if (this._albedoTexture) {
  46018. this._albedoTexture.dispose();
  46019. }
  46020. if (this._ambientTexture) {
  46021. this._ambientTexture.dispose();
  46022. }
  46023. if (this._opacityTexture) {
  46024. this._opacityTexture.dispose();
  46025. }
  46026. if (this._reflectionTexture) {
  46027. this._reflectionTexture.dispose();
  46028. }
  46029. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46030. this._environmentBRDFTexture.dispose();
  46031. }
  46032. if (this._emissiveTexture) {
  46033. this._emissiveTexture.dispose();
  46034. }
  46035. if (this._metallicTexture) {
  46036. this._metallicTexture.dispose();
  46037. }
  46038. if (this._reflectivityTexture) {
  46039. this._reflectivityTexture.dispose();
  46040. }
  46041. if (this._bumpTexture) {
  46042. this._bumpTexture.dispose();
  46043. }
  46044. if (this._lightmapTexture) {
  46045. this._lightmapTexture.dispose();
  46046. }
  46047. if (this._refractionTexture) {
  46048. this._refractionTexture.dispose();
  46049. }
  46050. }
  46051. this._renderTargets.dispose();
  46052. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46053. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46054. }
  46055. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46056. };
  46057. /**
  46058. * Stores the reflectivity values based on metallic roughness workflow.
  46059. */
  46060. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46061. __decorate([
  46062. BABYLON.serializeAsImageProcessingConfiguration()
  46063. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46064. __decorate([
  46065. BABYLON.serialize()
  46066. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46067. __decorate([
  46068. BABYLON.serialize()
  46069. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46070. return PBRBaseMaterial;
  46071. }(BABYLON.PushMaterial));
  46072. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46073. })(BABYLON || (BABYLON = {}));
  46074. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46075. var BABYLON;
  46076. (function (BABYLON) {
  46077. /**
  46078. * The Physically based simple base material of BJS.
  46079. *
  46080. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46081. * It is used as the base class for both the specGloss and metalRough conventions.
  46082. */
  46083. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46084. __extends(PBRBaseSimpleMaterial, _super);
  46085. /**
  46086. * Instantiates a new PBRMaterial instance.
  46087. *
  46088. * @param name The material name
  46089. * @param scene The scene the material will be use in.
  46090. */
  46091. function PBRBaseSimpleMaterial(name, scene) {
  46092. var _this = _super.call(this, name, scene) || this;
  46093. /**
  46094. * Number of Simultaneous lights allowed on the material.
  46095. */
  46096. _this.maxSimultaneousLights = 4;
  46097. /**
  46098. * If sets to true, disables all the lights affecting the material.
  46099. */
  46100. _this.disableLighting = false;
  46101. /**
  46102. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46103. */
  46104. _this.invertNormalMapX = false;
  46105. /**
  46106. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46107. */
  46108. _this.invertNormalMapY = false;
  46109. /**
  46110. * Emissivie color used to self-illuminate the model.
  46111. */
  46112. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46113. /**
  46114. * Occlusion Channel Strenght.
  46115. */
  46116. _this.occlusionStrength = 1.0;
  46117. _this.useLightmapAsShadowmap = false;
  46118. _this._useAlphaFromAlbedoTexture = true;
  46119. _this._useAmbientInGrayScale = true;
  46120. return _this;
  46121. }
  46122. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46123. /**
  46124. * Gets the current double sided mode.
  46125. */
  46126. get: function () {
  46127. return this._twoSidedLighting;
  46128. },
  46129. /**
  46130. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46131. */
  46132. set: function (value) {
  46133. if (this._twoSidedLighting === value) {
  46134. return;
  46135. }
  46136. this._twoSidedLighting = value;
  46137. this.backFaceCulling = !value;
  46138. this._markAllSubMeshesAsTexturesDirty();
  46139. },
  46140. enumerable: true,
  46141. configurable: true
  46142. });
  46143. /**
  46144. * Return the active textures of the material.
  46145. */
  46146. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46147. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46148. if (this.environmentTexture) {
  46149. activeTextures.push(this.environmentTexture);
  46150. }
  46151. if (this.normalTexture) {
  46152. activeTextures.push(this.normalTexture);
  46153. }
  46154. if (this.emissiveTexture) {
  46155. activeTextures.push(this.emissiveTexture);
  46156. }
  46157. if (this.occlusionTexture) {
  46158. activeTextures.push(this.occlusionTexture);
  46159. }
  46160. if (this.lightmapTexture) {
  46161. activeTextures.push(this.lightmapTexture);
  46162. }
  46163. return activeTextures;
  46164. };
  46165. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46166. if (_super.prototype.hasTexture.call(this, texture)) {
  46167. return true;
  46168. }
  46169. if (this.lightmapTexture === texture) {
  46170. return true;
  46171. }
  46172. return false;
  46173. };
  46174. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46175. return "PBRBaseSimpleMaterial";
  46176. };
  46177. __decorate([
  46178. BABYLON.serialize(),
  46179. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46180. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46181. __decorate([
  46182. BABYLON.serialize(),
  46183. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46184. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46185. __decorate([
  46186. BABYLON.serializeAsTexture(),
  46187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46188. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46189. __decorate([
  46190. BABYLON.serialize(),
  46191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46192. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46193. __decorate([
  46194. BABYLON.serialize(),
  46195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46196. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46197. __decorate([
  46198. BABYLON.serializeAsTexture(),
  46199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46200. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46201. __decorate([
  46202. BABYLON.serializeAsColor3("emissive"),
  46203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46204. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46205. __decorate([
  46206. BABYLON.serializeAsTexture(),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46208. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46209. __decorate([
  46210. BABYLON.serialize(),
  46211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46212. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46213. __decorate([
  46214. BABYLON.serializeAsTexture(),
  46215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46216. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46217. __decorate([
  46218. BABYLON.serialize(),
  46219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46220. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46221. __decorate([
  46222. BABYLON.serialize()
  46223. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46224. __decorate([
  46225. BABYLON.serializeAsTexture(),
  46226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46227. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46228. __decorate([
  46229. BABYLON.serialize(),
  46230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46231. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46232. return PBRBaseSimpleMaterial;
  46233. }(BABYLON.PBRBaseMaterial));
  46234. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46235. })(BABYLON || (BABYLON = {}));
  46236. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46237. var BABYLON;
  46238. (function (BABYLON) {
  46239. /**
  46240. * The Physically based material of BJS.
  46241. *
  46242. * This offers the main features of a standard PBR material.
  46243. * For more information, please refer to the documentation :
  46244. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46245. */
  46246. var PBRMaterial = /** @class */ (function (_super) {
  46247. __extends(PBRMaterial, _super);
  46248. /**
  46249. * Instantiates a new PBRMaterial instance.
  46250. *
  46251. * @param name The material name
  46252. * @param scene The scene the material will be use in.
  46253. */
  46254. function PBRMaterial(name, scene) {
  46255. var _this = _super.call(this, name, scene) || this;
  46256. /**
  46257. * Intensity of the direct lights e.g. the four lights available in your scene.
  46258. * This impacts both the direct diffuse and specular highlights.
  46259. */
  46260. _this.directIntensity = 1.0;
  46261. /**
  46262. * Intensity of the emissive part of the material.
  46263. * This helps controlling the emissive effect without modifying the emissive color.
  46264. */
  46265. _this.emissiveIntensity = 1.0;
  46266. /**
  46267. * Intensity of the environment e.g. how much the environment will light the object
  46268. * either through harmonics for rough material or through the refelction for shiny ones.
  46269. */
  46270. _this.environmentIntensity = 1.0;
  46271. /**
  46272. * This is a special control allowing the reduction of the specular highlights coming from the
  46273. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46274. */
  46275. _this.specularIntensity = 1.0;
  46276. /**
  46277. * Debug Control allowing disabling the bump map on this material.
  46278. */
  46279. _this.disableBumpMap = false;
  46280. /**
  46281. * AKA Occlusion Texture Intensity in other nomenclature.
  46282. */
  46283. _this.ambientTextureStrength = 1.0;
  46284. /**
  46285. * The color of a material in ambient lighting.
  46286. */
  46287. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46288. /**
  46289. * AKA Diffuse Color in other nomenclature.
  46290. */
  46291. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46292. /**
  46293. * AKA Specular Color in other nomenclature.
  46294. */
  46295. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46296. /**
  46297. * The color reflected from the material.
  46298. */
  46299. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46300. /**
  46301. * The color emitted from the material.
  46302. */
  46303. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46304. /**
  46305. * AKA Glossiness in other nomenclature.
  46306. */
  46307. _this.microSurface = 1.0;
  46308. /**
  46309. * source material index of refraction (IOR)' / 'destination material IOR.
  46310. */
  46311. _this.indexOfRefraction = 0.66;
  46312. /**
  46313. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46314. */
  46315. _this.invertRefractionY = false;
  46316. /**
  46317. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46318. * Materials half opaque for instance using refraction could benefit from this control.
  46319. */
  46320. _this.linkRefractionWithTransparency = false;
  46321. _this.useLightmapAsShadowmap = false;
  46322. /**
  46323. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46324. */
  46325. _this.useAlphaFromAlbedoTexture = false;
  46326. /**
  46327. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46328. */
  46329. _this.forceAlphaTest = false;
  46330. /**
  46331. * Defines the alpha limits in alpha test mode.
  46332. */
  46333. _this.alphaCutOff = 0.4;
  46334. /**
  46335. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46336. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46337. */
  46338. _this.useSpecularOverAlpha = true;
  46339. /**
  46340. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46341. */
  46342. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46343. /**
  46344. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46345. */
  46346. _this.useRoughnessFromMetallicTextureAlpha = true;
  46347. /**
  46348. * Specifies if the metallic texture contains the roughness information in its green channel.
  46349. */
  46350. _this.useRoughnessFromMetallicTextureGreen = false;
  46351. /**
  46352. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46353. */
  46354. _this.useMetallnessFromMetallicTextureBlue = false;
  46355. /**
  46356. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46357. */
  46358. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46359. /**
  46360. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46361. */
  46362. _this.useAmbientInGrayScale = false;
  46363. /**
  46364. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46365. * The material will try to infer what glossiness each pixel should be.
  46366. */
  46367. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46368. /**
  46369. * BJS is using an harcoded light falloff based on a manually sets up range.
  46370. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46371. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46372. */
  46373. _this.usePhysicalLightFalloff = true;
  46374. /**
  46375. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46376. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46377. */
  46378. _this.useRadianceOverAlpha = true;
  46379. /**
  46380. * Allows using an object space normal map (instead of tangent space).
  46381. */
  46382. _this.useObjectSpaceNormalMap = false;
  46383. /**
  46384. * Allows using the bump map in parallax mode.
  46385. */
  46386. _this.useParallax = false;
  46387. /**
  46388. * Allows using the bump map in parallax occlusion mode.
  46389. */
  46390. _this.useParallaxOcclusion = false;
  46391. /**
  46392. * Controls the scale bias of the parallax mode.
  46393. */
  46394. _this.parallaxScaleBias = 0.05;
  46395. /**
  46396. * If sets to true, disables all the lights affecting the material.
  46397. */
  46398. _this.disableLighting = false;
  46399. /**
  46400. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46401. */
  46402. _this.forceIrradianceInFragment = false;
  46403. /**
  46404. * Number of Simultaneous lights allowed on the material.
  46405. */
  46406. _this.maxSimultaneousLights = 4;
  46407. /**
  46408. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46409. */
  46410. _this.invertNormalMapX = false;
  46411. /**
  46412. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46413. */
  46414. _this.invertNormalMapY = false;
  46415. /**
  46416. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46417. */
  46418. _this.twoSidedLighting = false;
  46419. /**
  46420. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46421. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46422. */
  46423. _this.useAlphaFresnel = false;
  46424. /**
  46425. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46426. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46427. */
  46428. _this.useLinearAlphaFresnel = false;
  46429. /**
  46430. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46431. * And/Or occlude the blended part.
  46432. */
  46433. _this.environmentBRDFTexture = null;
  46434. /**
  46435. * Force normal to face away from face.
  46436. */
  46437. _this.forceNormalForward = false;
  46438. /**
  46439. * Enables specular anti aliasing in the PBR shader.
  46440. * It will both interacts on the Geometry for analytical and IBL lighting.
  46441. * It also prefilter the roughness map based on the bump values.
  46442. */
  46443. _this.enableSpecularAntiAliasing = false;
  46444. /**
  46445. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46446. * makes the reflect vector face the model (under horizon).
  46447. */
  46448. _this.useHorizonOcclusion = true;
  46449. /**
  46450. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46451. * too much the area relying on ambient texture to define their ambient occlusion.
  46452. */
  46453. _this.useRadianceOcclusion = true;
  46454. /**
  46455. * If set to true, no lighting calculations will be applied.
  46456. */
  46457. _this.unlit = false;
  46458. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46459. return _this;
  46460. }
  46461. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46462. /**
  46463. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46464. */
  46465. get: function () {
  46466. return this._PBRMATERIAL_OPAQUE;
  46467. },
  46468. enumerable: true,
  46469. configurable: true
  46470. });
  46471. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46472. /**
  46473. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46474. */
  46475. get: function () {
  46476. return this._PBRMATERIAL_ALPHATEST;
  46477. },
  46478. enumerable: true,
  46479. configurable: true
  46480. });
  46481. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46482. /**
  46483. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46484. */
  46485. get: function () {
  46486. return this._PBRMATERIAL_ALPHABLEND;
  46487. },
  46488. enumerable: true,
  46489. configurable: true
  46490. });
  46491. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46492. /**
  46493. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46494. * They are also discarded below the alpha cutoff threshold to improve performances.
  46495. */
  46496. get: function () {
  46497. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46498. },
  46499. enumerable: true,
  46500. configurable: true
  46501. });
  46502. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46503. /**
  46504. * Gets the image processing configuration used either in this material.
  46505. */
  46506. get: function () {
  46507. return this._imageProcessingConfiguration;
  46508. },
  46509. /**
  46510. * Sets the Default image processing configuration used either in the this material.
  46511. *
  46512. * If sets to null, the scene one is in use.
  46513. */
  46514. set: function (value) {
  46515. this._attachImageProcessingConfiguration(value);
  46516. // Ensure the effect will be rebuilt.
  46517. this._markAllSubMeshesAsTexturesDirty();
  46518. },
  46519. enumerable: true,
  46520. configurable: true
  46521. });
  46522. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46523. /**
  46524. * Gets wether the color curves effect is enabled.
  46525. */
  46526. get: function () {
  46527. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46528. },
  46529. /**
  46530. * Sets wether the color curves effect is enabled.
  46531. */
  46532. set: function (value) {
  46533. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46534. },
  46535. enumerable: true,
  46536. configurable: true
  46537. });
  46538. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46539. /**
  46540. * Gets wether the color grading effect is enabled.
  46541. */
  46542. get: function () {
  46543. return this.imageProcessingConfiguration.colorGradingEnabled;
  46544. },
  46545. /**
  46546. * Gets wether the color grading effect is enabled.
  46547. */
  46548. set: function (value) {
  46549. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46550. },
  46551. enumerable: true,
  46552. configurable: true
  46553. });
  46554. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46555. /**
  46556. * Gets wether tonemapping is enabled or not.
  46557. */
  46558. get: function () {
  46559. return this._imageProcessingConfiguration.toneMappingEnabled;
  46560. },
  46561. /**
  46562. * Sets wether tonemapping is enabled or not
  46563. */
  46564. set: function (value) {
  46565. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46566. },
  46567. enumerable: true,
  46568. configurable: true
  46569. });
  46570. ;
  46571. ;
  46572. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46573. /**
  46574. * The camera exposure used on this material.
  46575. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46576. * This corresponds to a photographic exposure.
  46577. */
  46578. get: function () {
  46579. return this._imageProcessingConfiguration.exposure;
  46580. },
  46581. /**
  46582. * The camera exposure used on this material.
  46583. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46584. * This corresponds to a photographic exposure.
  46585. */
  46586. set: function (value) {
  46587. this._imageProcessingConfiguration.exposure = value;
  46588. },
  46589. enumerable: true,
  46590. configurable: true
  46591. });
  46592. ;
  46593. ;
  46594. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46595. /**
  46596. * Gets The camera contrast used on this material.
  46597. */
  46598. get: function () {
  46599. return this._imageProcessingConfiguration.contrast;
  46600. },
  46601. /**
  46602. * Sets The camera contrast used on this material.
  46603. */
  46604. set: function (value) {
  46605. this._imageProcessingConfiguration.contrast = value;
  46606. },
  46607. enumerable: true,
  46608. configurable: true
  46609. });
  46610. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46611. /**
  46612. * Gets the Color Grading 2D Lookup Texture.
  46613. */
  46614. get: function () {
  46615. return this._imageProcessingConfiguration.colorGradingTexture;
  46616. },
  46617. /**
  46618. * Sets the Color Grading 2D Lookup Texture.
  46619. */
  46620. set: function (value) {
  46621. this._imageProcessingConfiguration.colorGradingTexture = value;
  46622. },
  46623. enumerable: true,
  46624. configurable: true
  46625. });
  46626. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46627. /**
  46628. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46629. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46630. * 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;
  46631. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46632. */
  46633. get: function () {
  46634. return this._imageProcessingConfiguration.colorCurves;
  46635. },
  46636. /**
  46637. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46638. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46639. * 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;
  46640. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46641. */
  46642. set: function (value) {
  46643. this._imageProcessingConfiguration.colorCurves = value;
  46644. },
  46645. enumerable: true,
  46646. configurable: true
  46647. });
  46648. /**
  46649. * Returns the name of this material class.
  46650. */
  46651. PBRMaterial.prototype.getClassName = function () {
  46652. return "PBRMaterial";
  46653. };
  46654. /**
  46655. * Returns an array of the actively used textures.
  46656. * @returns - Array of BaseTextures
  46657. */
  46658. PBRMaterial.prototype.getActiveTextures = function () {
  46659. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46660. if (this._albedoTexture) {
  46661. activeTextures.push(this._albedoTexture);
  46662. }
  46663. if (this._ambientTexture) {
  46664. activeTextures.push(this._ambientTexture);
  46665. }
  46666. if (this._opacityTexture) {
  46667. activeTextures.push(this._opacityTexture);
  46668. }
  46669. if (this._reflectionTexture) {
  46670. activeTextures.push(this._reflectionTexture);
  46671. }
  46672. if (this._emissiveTexture) {
  46673. activeTextures.push(this._emissiveTexture);
  46674. }
  46675. if (this._reflectivityTexture) {
  46676. activeTextures.push(this._reflectivityTexture);
  46677. }
  46678. if (this._metallicTexture) {
  46679. activeTextures.push(this._metallicTexture);
  46680. }
  46681. if (this._microSurfaceTexture) {
  46682. activeTextures.push(this._microSurfaceTexture);
  46683. }
  46684. if (this._bumpTexture) {
  46685. activeTextures.push(this._bumpTexture);
  46686. }
  46687. if (this._lightmapTexture) {
  46688. activeTextures.push(this._lightmapTexture);
  46689. }
  46690. if (this._refractionTexture) {
  46691. activeTextures.push(this._refractionTexture);
  46692. }
  46693. return activeTextures;
  46694. };
  46695. /**
  46696. * Checks to see if a texture is used in the material.
  46697. * @param texture - Base texture to use.
  46698. * @returns - Boolean specifying if a texture is used in the material.
  46699. */
  46700. PBRMaterial.prototype.hasTexture = function (texture) {
  46701. if (_super.prototype.hasTexture.call(this, texture)) {
  46702. return true;
  46703. }
  46704. if (this._albedoTexture === texture) {
  46705. return true;
  46706. }
  46707. if (this._ambientTexture === texture) {
  46708. return true;
  46709. }
  46710. if (this._opacityTexture === texture) {
  46711. return true;
  46712. }
  46713. if (this._reflectionTexture === texture) {
  46714. return true;
  46715. }
  46716. if (this._reflectivityTexture === texture) {
  46717. return true;
  46718. }
  46719. if (this._metallicTexture === texture) {
  46720. return true;
  46721. }
  46722. if (this._microSurfaceTexture === texture) {
  46723. return true;
  46724. }
  46725. if (this._bumpTexture === texture) {
  46726. return true;
  46727. }
  46728. if (this._lightmapTexture === texture) {
  46729. return true;
  46730. }
  46731. if (this._refractionTexture === texture) {
  46732. return true;
  46733. }
  46734. return false;
  46735. };
  46736. /**
  46737. * Makes a duplicate of the current material.
  46738. * @param name - name to use for the new material.
  46739. */
  46740. PBRMaterial.prototype.clone = function (name) {
  46741. var _this = this;
  46742. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46743. clone.id = name;
  46744. clone.name = name;
  46745. return clone;
  46746. };
  46747. /**
  46748. * Serializes this PBR Material.
  46749. * @returns - An object with the serialized material.
  46750. */
  46751. PBRMaterial.prototype.serialize = function () {
  46752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46753. serializationObject.customType = "BABYLON.PBRMaterial";
  46754. return serializationObject;
  46755. };
  46756. // Statics
  46757. /**
  46758. * Parses a PBR Material from a serialized object.
  46759. * @param source - Serialized object.
  46760. * @param scene - BJS scene instance.
  46761. * @param rootUrl - url for the scene object
  46762. * @returns - PBRMaterial
  46763. */
  46764. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46765. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46766. };
  46767. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46768. /**
  46769. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46770. */
  46771. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46772. /**
  46773. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46774. */
  46775. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46776. /**
  46777. * 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.
  46778. * They are also discarded below the alpha cutoff threshold to improve performances.
  46779. */
  46780. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46781. __decorate([
  46782. BABYLON.serialize(),
  46783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46784. ], PBRMaterial.prototype, "directIntensity", void 0);
  46785. __decorate([
  46786. BABYLON.serialize(),
  46787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46788. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46789. __decorate([
  46790. BABYLON.serialize(),
  46791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46792. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46793. __decorate([
  46794. BABYLON.serialize(),
  46795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46796. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46797. __decorate([
  46798. BABYLON.serialize(),
  46799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46800. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46801. __decorate([
  46802. BABYLON.serializeAsTexture(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46804. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46805. __decorate([
  46806. BABYLON.serializeAsTexture(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46808. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46809. __decorate([
  46810. BABYLON.serialize(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46813. __decorate([
  46814. BABYLON.serializeAsTexture(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46816. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46821. __decorate([
  46822. BABYLON.serializeAsTexture(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46824. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46825. __decorate([
  46826. BABYLON.serializeAsTexture(),
  46827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46828. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46829. __decorate([
  46830. BABYLON.serializeAsTexture(),
  46831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46832. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46833. __decorate([
  46834. BABYLON.serialize(),
  46835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46836. ], PBRMaterial.prototype, "metallic", void 0);
  46837. __decorate([
  46838. BABYLON.serialize(),
  46839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46840. ], PBRMaterial.prototype, "roughness", void 0);
  46841. __decorate([
  46842. BABYLON.serializeAsTexture(),
  46843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46844. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsTexture(),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46848. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46849. __decorate([
  46850. BABYLON.serializeAsTexture(),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46852. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46853. __decorate([
  46854. BABYLON.serializeAsTexture(),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46857. __decorate([
  46858. BABYLON.serializeAsColor3("ambient"),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "ambientColor", void 0);
  46861. __decorate([
  46862. BABYLON.serializeAsColor3("albedo"),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "albedoColor", void 0);
  46865. __decorate([
  46866. BABYLON.serializeAsColor3("reflectivity"),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46868. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46869. __decorate([
  46870. BABYLON.serializeAsColor3("reflection"),
  46871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46872. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46873. __decorate([
  46874. BABYLON.serializeAsColor3("emissive"),
  46875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46876. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46877. __decorate([
  46878. BABYLON.serialize(),
  46879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46880. ], PBRMaterial.prototype, "microSurface", void 0);
  46881. __decorate([
  46882. BABYLON.serialize(),
  46883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46884. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46885. __decorate([
  46886. BABYLON.serialize(),
  46887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46888. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46889. __decorate([
  46890. BABYLON.serialize(),
  46891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46892. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46893. __decorate([
  46894. BABYLON.serialize(),
  46895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46896. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46897. __decorate([
  46898. BABYLON.serialize(),
  46899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46900. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46901. __decorate([
  46902. BABYLON.serialize(),
  46903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46904. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46905. __decorate([
  46906. BABYLON.serialize(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46908. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46909. __decorate([
  46910. BABYLON.serialize(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46912. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46921. __decorate([
  46922. BABYLON.serialize(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46924. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46925. __decorate([
  46926. BABYLON.serialize(),
  46927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46928. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46929. __decorate([
  46930. BABYLON.serialize(),
  46931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46932. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46933. __decorate([
  46934. BABYLON.serialize(),
  46935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46936. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46937. __decorate([
  46938. BABYLON.serialize(),
  46939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46940. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46941. __decorate([
  46942. BABYLON.serialize(),
  46943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46944. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46945. __decorate([
  46946. BABYLON.serialize(),
  46947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46948. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46949. __decorate([
  46950. BABYLON.serialize(),
  46951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46952. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46953. __decorate([
  46954. BABYLON.serialize(),
  46955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46956. ], PBRMaterial.prototype, "useParallax", void 0);
  46957. __decorate([
  46958. BABYLON.serialize(),
  46959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46960. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46961. __decorate([
  46962. BABYLON.serialize(),
  46963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46964. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46965. __decorate([
  46966. BABYLON.serialize(),
  46967. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46968. ], PBRMaterial.prototype, "disableLighting", void 0);
  46969. __decorate([
  46970. BABYLON.serialize(),
  46971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46972. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46973. __decorate([
  46974. BABYLON.serialize(),
  46975. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46976. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46977. __decorate([
  46978. BABYLON.serialize(),
  46979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46980. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46981. __decorate([
  46982. BABYLON.serialize(),
  46983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46984. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46985. __decorate([
  46986. BABYLON.serialize(),
  46987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46988. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46989. __decorate([
  46990. BABYLON.serialize(),
  46991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46992. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46993. __decorate([
  46994. BABYLON.serialize(),
  46995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46996. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46997. __decorate([
  46998. BABYLON.serializeAsTexture(),
  46999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47000. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47001. __decorate([
  47002. BABYLON.serialize(),
  47003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47004. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47005. __decorate([
  47006. BABYLON.serialize(),
  47007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47008. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47009. __decorate([
  47010. BABYLON.serialize(),
  47011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47012. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47013. __decorate([
  47014. BABYLON.serialize(),
  47015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47016. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47017. __decorate([
  47018. BABYLON.serialize(),
  47019. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47020. ], PBRMaterial.prototype, "unlit", void 0);
  47021. return PBRMaterial;
  47022. }(BABYLON.PBRBaseMaterial));
  47023. BABYLON.PBRMaterial = PBRMaterial;
  47024. })(BABYLON || (BABYLON = {}));
  47025. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47026. var BABYLON;
  47027. (function (BABYLON) {
  47028. /**
  47029. * The PBR material of BJS following the metal roughness convention.
  47030. *
  47031. * This fits to the PBR convention in the GLTF definition:
  47032. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47033. */
  47034. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47035. __extends(PBRMetallicRoughnessMaterial, _super);
  47036. /**
  47037. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47038. *
  47039. * @param name The material name
  47040. * @param scene The scene the material will be use in.
  47041. */
  47042. function PBRMetallicRoughnessMaterial(name, scene) {
  47043. var _this = _super.call(this, name, scene) || this;
  47044. _this._useRoughnessFromMetallicTextureAlpha = false;
  47045. _this._useRoughnessFromMetallicTextureGreen = true;
  47046. _this._useMetallnessFromMetallicTextureBlue = true;
  47047. _this.metallic = 1.0;
  47048. _this.roughness = 1.0;
  47049. return _this;
  47050. }
  47051. /**
  47052. * Return the currrent class name of the material.
  47053. */
  47054. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47055. return "PBRMetallicRoughnessMaterial";
  47056. };
  47057. /**
  47058. * Return the active textures of the material.
  47059. */
  47060. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47061. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47062. if (this.baseTexture) {
  47063. activeTextures.push(this.baseTexture);
  47064. }
  47065. if (this.metallicRoughnessTexture) {
  47066. activeTextures.push(this.metallicRoughnessTexture);
  47067. }
  47068. return activeTextures;
  47069. };
  47070. /**
  47071. * Checks to see if a texture is used in the material.
  47072. * @param texture - Base texture to use.
  47073. * @returns - Boolean specifying if a texture is used in the material.
  47074. */
  47075. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47076. if (_super.prototype.hasTexture.call(this, texture)) {
  47077. return true;
  47078. }
  47079. if (this.baseTexture === texture) {
  47080. return true;
  47081. }
  47082. if (this.metallicRoughnessTexture === texture) {
  47083. return true;
  47084. }
  47085. return false;
  47086. };
  47087. /**
  47088. * Makes a duplicate of the current material.
  47089. * @param name - name to use for the new material.
  47090. */
  47091. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47092. var _this = this;
  47093. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47094. clone.id = name;
  47095. clone.name = name;
  47096. return clone;
  47097. };
  47098. /**
  47099. * Serialize the material to a parsable JSON object.
  47100. */
  47101. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47102. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47103. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47104. return serializationObject;
  47105. };
  47106. /**
  47107. * Parses a JSON object correponding to the serialize function.
  47108. */
  47109. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47110. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47111. };
  47112. __decorate([
  47113. BABYLON.serializeAsColor3(),
  47114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47115. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47116. __decorate([
  47117. BABYLON.serializeAsTexture(),
  47118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47119. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47120. __decorate([
  47121. BABYLON.serialize(),
  47122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47123. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47124. __decorate([
  47125. BABYLON.serialize(),
  47126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47127. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47128. __decorate([
  47129. BABYLON.serializeAsTexture(),
  47130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47131. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47132. return PBRMetallicRoughnessMaterial;
  47133. }(BABYLON.PBRBaseSimpleMaterial));
  47134. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47135. })(BABYLON || (BABYLON = {}));
  47136. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47137. var BABYLON;
  47138. (function (BABYLON) {
  47139. /**
  47140. * The PBR material of BJS following the specular glossiness convention.
  47141. *
  47142. * This fits to the PBR convention in the GLTF definition:
  47143. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47144. */
  47145. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47146. __extends(PBRSpecularGlossinessMaterial, _super);
  47147. /**
  47148. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47149. *
  47150. * @param name The material name
  47151. * @param scene The scene the material will be use in.
  47152. */
  47153. function PBRSpecularGlossinessMaterial(name, scene) {
  47154. var _this = _super.call(this, name, scene) || this;
  47155. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47156. return _this;
  47157. }
  47158. /**
  47159. * Return the currrent class name of the material.
  47160. */
  47161. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47162. return "PBRSpecularGlossinessMaterial";
  47163. };
  47164. /**
  47165. * Return the active textures of the material.
  47166. */
  47167. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47168. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47169. if (this.diffuseTexture) {
  47170. activeTextures.push(this.diffuseTexture);
  47171. }
  47172. if (this.specularGlossinessTexture) {
  47173. activeTextures.push(this.specularGlossinessTexture);
  47174. }
  47175. return activeTextures;
  47176. };
  47177. /**
  47178. * Checks to see if a texture is used in the material.
  47179. * @param texture - Base texture to use.
  47180. * @returns - Boolean specifying if a texture is used in the material.
  47181. */
  47182. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47183. if (_super.prototype.hasTexture.call(this, texture)) {
  47184. return true;
  47185. }
  47186. if (this.diffuseTexture === texture) {
  47187. return true;
  47188. }
  47189. if (this.specularGlossinessTexture === texture) {
  47190. return true;
  47191. }
  47192. return false;
  47193. };
  47194. /**
  47195. * Makes a duplicate of the current material.
  47196. * @param name - name to use for the new material.
  47197. */
  47198. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47199. var _this = this;
  47200. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47201. clone.id = name;
  47202. clone.name = name;
  47203. return clone;
  47204. };
  47205. /**
  47206. * Serialize the material to a parsable JSON object.
  47207. */
  47208. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47210. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47211. return serializationObject;
  47212. };
  47213. /**
  47214. * Parses a JSON object correponding to the serialize function.
  47215. */
  47216. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47217. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47218. };
  47219. __decorate([
  47220. BABYLON.serializeAsColor3("diffuse"),
  47221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47222. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47223. __decorate([
  47224. BABYLON.serializeAsTexture(),
  47225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47226. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47227. __decorate([
  47228. BABYLON.serializeAsColor3("specular"),
  47229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47230. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47231. __decorate([
  47232. BABYLON.serialize(),
  47233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47234. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47235. __decorate([
  47236. BABYLON.serializeAsTexture(),
  47237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47238. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47239. return PBRSpecularGlossinessMaterial;
  47240. }(BABYLON.PBRBaseSimpleMaterial));
  47241. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47242. })(BABYLON || (BABYLON = {}));
  47243. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47244. var BABYLON;
  47245. (function (BABYLON) {
  47246. BABYLON.CameraInputTypes = {};
  47247. var CameraInputsManager = /** @class */ (function () {
  47248. function CameraInputsManager(camera) {
  47249. this.attached = {};
  47250. this.camera = camera;
  47251. this.checkInputs = function () { };
  47252. }
  47253. /**
  47254. * Add an input method to a camera.
  47255. * builtin inputs example: camera.inputs.addGamepad();
  47256. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47257. * @param input camera input method
  47258. */
  47259. CameraInputsManager.prototype.add = function (input) {
  47260. var type = input.getSimpleName();
  47261. if (this.attached[type]) {
  47262. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47263. return;
  47264. }
  47265. this.attached[type] = input;
  47266. input.camera = this.camera;
  47267. //for checkInputs, we are dynamically creating a function
  47268. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47269. if (input.checkInputs) {
  47270. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47271. }
  47272. if (this.attachedElement) {
  47273. input.attachControl(this.attachedElement);
  47274. }
  47275. };
  47276. /**
  47277. * Remove a specific input method from a camera
  47278. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47279. * @param inputToRemove camera input method
  47280. */
  47281. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47282. for (var cam in this.attached) {
  47283. var input = this.attached[cam];
  47284. if (input === inputToRemove) {
  47285. input.detachControl(this.attachedElement);
  47286. input.camera = null;
  47287. delete this.attached[cam];
  47288. this.rebuildInputCheck();
  47289. }
  47290. }
  47291. };
  47292. CameraInputsManager.prototype.removeByType = function (inputType) {
  47293. for (var cam in this.attached) {
  47294. var input = this.attached[cam];
  47295. if (input.getClassName() === inputType) {
  47296. input.detachControl(this.attachedElement);
  47297. input.camera = null;
  47298. delete this.attached[cam];
  47299. this.rebuildInputCheck();
  47300. }
  47301. }
  47302. };
  47303. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47304. var current = this.checkInputs;
  47305. return function () {
  47306. current();
  47307. fn();
  47308. };
  47309. };
  47310. CameraInputsManager.prototype.attachInput = function (input) {
  47311. if (this.attachedElement) {
  47312. input.attachControl(this.attachedElement, this.noPreventDefault);
  47313. }
  47314. };
  47315. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47316. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47317. if (this.attachedElement) {
  47318. return;
  47319. }
  47320. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47321. this.attachedElement = element;
  47322. this.noPreventDefault = noPreventDefault;
  47323. for (var cam in this.attached) {
  47324. this.attached[cam].attachControl(element, noPreventDefault);
  47325. }
  47326. };
  47327. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47328. if (disconnect === void 0) { disconnect = false; }
  47329. if (this.attachedElement !== element) {
  47330. return;
  47331. }
  47332. for (var cam in this.attached) {
  47333. this.attached[cam].detachControl(element);
  47334. if (disconnect) {
  47335. this.attached[cam].camera = null;
  47336. }
  47337. }
  47338. this.attachedElement = null;
  47339. };
  47340. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47341. this.checkInputs = function () { };
  47342. for (var cam in this.attached) {
  47343. var input = this.attached[cam];
  47344. if (input.checkInputs) {
  47345. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47346. }
  47347. }
  47348. };
  47349. /**
  47350. * Remove all attached input methods from a camera
  47351. */
  47352. CameraInputsManager.prototype.clear = function () {
  47353. if (this.attachedElement) {
  47354. this.detachElement(this.attachedElement, true);
  47355. }
  47356. this.attached = {};
  47357. this.attachedElement = null;
  47358. this.checkInputs = function () { };
  47359. };
  47360. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47361. var inputs = {};
  47362. for (var cam in this.attached) {
  47363. var input = this.attached[cam];
  47364. var res = BABYLON.SerializationHelper.Serialize(input);
  47365. inputs[input.getClassName()] = res;
  47366. }
  47367. serializedCamera.inputsmgr = inputs;
  47368. };
  47369. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47370. var parsedInputs = parsedCamera.inputsmgr;
  47371. if (parsedInputs) {
  47372. this.clear();
  47373. for (var n in parsedInputs) {
  47374. var construct = BABYLON.CameraInputTypes[n];
  47375. if (construct) {
  47376. var parsedinput = parsedInputs[n];
  47377. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47378. this.add(input);
  47379. }
  47380. }
  47381. }
  47382. else {
  47383. //2016-03-08 this part is for managing backward compatibility
  47384. for (var n in this.attached) {
  47385. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47386. if (construct) {
  47387. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47388. this.remove(this.attached[n]);
  47389. this.add(input);
  47390. }
  47391. }
  47392. }
  47393. };
  47394. return CameraInputsManager;
  47395. }());
  47396. BABYLON.CameraInputsManager = CameraInputsManager;
  47397. })(BABYLON || (BABYLON = {}));
  47398. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47399. var BABYLON;
  47400. (function (BABYLON) {
  47401. var TargetCamera = /** @class */ (function (_super) {
  47402. __extends(TargetCamera, _super);
  47403. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47404. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47405. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47406. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47407. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47408. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47409. _this.speed = 2.0;
  47410. _this.noRotationConstraint = false;
  47411. _this.lockedTarget = null;
  47412. _this._currentTarget = BABYLON.Vector3.Zero();
  47413. _this._viewMatrix = BABYLON.Matrix.Zero();
  47414. _this._camMatrix = BABYLON.Matrix.Zero();
  47415. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47416. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47417. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47418. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47419. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47420. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47421. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47422. return _this;
  47423. }
  47424. TargetCamera.prototype.getFrontPosition = function (distance) {
  47425. this.getWorldMatrix();
  47426. var direction = this.getTarget().subtract(this.position);
  47427. direction.normalize();
  47428. direction.scaleInPlace(distance);
  47429. return this.globalPosition.add(direction);
  47430. };
  47431. TargetCamera.prototype._getLockedTargetPosition = function () {
  47432. if (!this.lockedTarget) {
  47433. return null;
  47434. }
  47435. if (this.lockedTarget.absolutePosition) {
  47436. this.lockedTarget.computeWorldMatrix();
  47437. }
  47438. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47439. };
  47440. TargetCamera.prototype.storeState = function () {
  47441. this._storedPosition = this.position.clone();
  47442. this._storedRotation = this.rotation.clone();
  47443. if (this.rotationQuaternion) {
  47444. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47445. }
  47446. return _super.prototype.storeState.call(this);
  47447. };
  47448. /**
  47449. * Restored camera state. You must call storeState() first
  47450. */
  47451. TargetCamera.prototype._restoreStateValues = function () {
  47452. if (!_super.prototype._restoreStateValues.call(this)) {
  47453. return false;
  47454. }
  47455. this.position = this._storedPosition.clone();
  47456. this.rotation = this._storedRotation.clone();
  47457. if (this.rotationQuaternion) {
  47458. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47459. }
  47460. this.cameraDirection.copyFromFloats(0, 0, 0);
  47461. this.cameraRotation.copyFromFloats(0, 0);
  47462. return true;
  47463. };
  47464. // Cache
  47465. TargetCamera.prototype._initCache = function () {
  47466. _super.prototype._initCache.call(this);
  47467. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47468. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47469. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47470. };
  47471. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47472. if (!ignoreParentClass) {
  47473. _super.prototype._updateCache.call(this);
  47474. }
  47475. var lockedTargetPosition = this._getLockedTargetPosition();
  47476. if (!lockedTargetPosition) {
  47477. this._cache.lockedTarget = null;
  47478. }
  47479. else {
  47480. if (!this._cache.lockedTarget) {
  47481. this._cache.lockedTarget = lockedTargetPosition.clone();
  47482. }
  47483. else {
  47484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47485. }
  47486. }
  47487. this._cache.rotation.copyFrom(this.rotation);
  47488. if (this.rotationQuaternion)
  47489. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47490. };
  47491. // Synchronized
  47492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47494. return false;
  47495. }
  47496. var lockedTargetPosition = this._getLockedTargetPosition();
  47497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47498. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47499. };
  47500. // Methods
  47501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47502. var engine = this.getEngine();
  47503. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47504. };
  47505. // Target
  47506. TargetCamera.prototype.setTarget = function (target) {
  47507. this.upVector.normalize();
  47508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47509. this._camMatrix.invert();
  47510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47511. var vDir = target.subtract(this.position);
  47512. if (vDir.x >= 0.0) {
  47513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47514. }
  47515. else {
  47516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47517. }
  47518. this.rotation.z = 0;
  47519. if (isNaN(this.rotation.x)) {
  47520. this.rotation.x = 0;
  47521. }
  47522. if (isNaN(this.rotation.y)) {
  47523. this.rotation.y = 0;
  47524. }
  47525. if (isNaN(this.rotation.z)) {
  47526. this.rotation.z = 0;
  47527. }
  47528. if (this.rotationQuaternion) {
  47529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47530. }
  47531. };
  47532. /**
  47533. * Return the current target position of the camera. This value is expressed in local space.
  47534. */
  47535. TargetCamera.prototype.getTarget = function () {
  47536. return this._currentTarget;
  47537. };
  47538. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47539. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47540. };
  47541. TargetCamera.prototype._updatePosition = function () {
  47542. if (this.parent) {
  47543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47546. return;
  47547. }
  47548. this.position.addInPlace(this.cameraDirection);
  47549. };
  47550. TargetCamera.prototype._checkInputs = function () {
  47551. var needToMove = this._decideIfNeedsToMove();
  47552. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47553. // Move
  47554. if (needToMove) {
  47555. this._updatePosition();
  47556. }
  47557. // Rotate
  47558. if (needToRotate) {
  47559. this.rotation.x += this.cameraRotation.x;
  47560. this.rotation.y += this.cameraRotation.y;
  47561. //rotate, if quaternion is set and rotation was used
  47562. if (this.rotationQuaternion) {
  47563. var len = this.rotation.lengthSquared();
  47564. if (len) {
  47565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47566. }
  47567. }
  47568. if (!this.noRotationConstraint) {
  47569. var limit = (Math.PI / 2) * 0.95;
  47570. if (this.rotation.x > limit)
  47571. this.rotation.x = limit;
  47572. if (this.rotation.x < -limit)
  47573. this.rotation.x = -limit;
  47574. }
  47575. }
  47576. // Inertia
  47577. if (needToMove) {
  47578. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47579. this.cameraDirection.x = 0;
  47580. }
  47581. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47582. this.cameraDirection.y = 0;
  47583. }
  47584. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47585. this.cameraDirection.z = 0;
  47586. }
  47587. this.cameraDirection.scaleInPlace(this.inertia);
  47588. }
  47589. if (needToRotate) {
  47590. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47591. this.cameraRotation.x = 0;
  47592. }
  47593. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47594. this.cameraRotation.y = 0;
  47595. }
  47596. this.cameraRotation.scaleInPlace(this.inertia);
  47597. }
  47598. _super.prototype._checkInputs.call(this);
  47599. };
  47600. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47601. if (this.rotationQuaternion) {
  47602. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47603. }
  47604. else {
  47605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47606. }
  47607. //update the up vector!
  47608. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47609. };
  47610. TargetCamera.prototype._getViewMatrix = function () {
  47611. if (this.lockedTarget) {
  47612. this.setTarget(this._getLockedTargetPosition());
  47613. }
  47614. // Compute
  47615. this._updateCameraRotationMatrix();
  47616. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47617. // Computing target and final matrix
  47618. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47619. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47620. return this._viewMatrix;
  47621. };
  47622. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47623. if (this.parent) {
  47624. var parentWorldMatrix = this.parent.getWorldMatrix();
  47625. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47626. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47627. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47628. this._markSyncedWithParent();
  47629. }
  47630. else {
  47631. this._globalPosition.copyFrom(this.position);
  47632. this._globalCurrentTarget.copyFrom(target);
  47633. this._globalCurrentUpVector.copyFrom(up);
  47634. }
  47635. if (this.getScene().useRightHandedSystem) {
  47636. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47637. }
  47638. else {
  47639. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47640. }
  47641. };
  47642. /**
  47643. * @override
  47644. * Override Camera.createRigCamera
  47645. */
  47646. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47647. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47648. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47649. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47650. if (!this.rotationQuaternion) {
  47651. this.rotationQuaternion = new BABYLON.Quaternion();
  47652. }
  47653. rigCamera._cameraRigParams = {};
  47654. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47655. }
  47656. return rigCamera;
  47657. }
  47658. return null;
  47659. };
  47660. /**
  47661. * @override
  47662. * Override Camera._updateRigCameras
  47663. */
  47664. TargetCamera.prototype._updateRigCameras = function () {
  47665. var camLeft = this._rigCameras[0];
  47666. var camRight = this._rigCameras[1];
  47667. switch (this.cameraRigMode) {
  47668. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47669. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47670. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47671. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47672. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47673. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47674. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47675. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47676. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47677. camLeft.setTarget(this.getTarget());
  47678. camRight.setTarget(this.getTarget());
  47679. break;
  47680. case BABYLON.Camera.RIG_MODE_VR:
  47681. if (camLeft.rotationQuaternion) {
  47682. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47683. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47684. }
  47685. else {
  47686. camLeft.rotation.copyFrom(this.rotation);
  47687. camRight.rotation.copyFrom(this.rotation);
  47688. }
  47689. camLeft.position.copyFrom(this.position);
  47690. camRight.position.copyFrom(this.position);
  47691. break;
  47692. }
  47693. _super.prototype._updateRigCameras.call(this);
  47694. };
  47695. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47696. if (!this._rigCamTransformMatrix) {
  47697. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47698. }
  47699. var target = this.getTarget();
  47700. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47701. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47702. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47703. };
  47704. TargetCamera.prototype.getClassName = function () {
  47705. return "TargetCamera";
  47706. };
  47707. __decorate([
  47708. BABYLON.serializeAsVector3()
  47709. ], TargetCamera.prototype, "rotation", void 0);
  47710. __decorate([
  47711. BABYLON.serialize()
  47712. ], TargetCamera.prototype, "speed", void 0);
  47713. __decorate([
  47714. BABYLON.serializeAsMeshReference("lockedTargetId")
  47715. ], TargetCamera.prototype, "lockedTarget", void 0);
  47716. return TargetCamera;
  47717. }(BABYLON.Camera));
  47718. BABYLON.TargetCamera = TargetCamera;
  47719. })(BABYLON || (BABYLON = {}));
  47720. //# sourceMappingURL=babylon.targetCamera.js.map
  47721. var BABYLON;
  47722. (function (BABYLON) {
  47723. var FreeCameraMouseInput = /** @class */ (function () {
  47724. function FreeCameraMouseInput(touchEnabled) {
  47725. if (touchEnabled === void 0) { touchEnabled = true; }
  47726. this.touchEnabled = touchEnabled;
  47727. this.buttons = [0, 1, 2];
  47728. this.angularSensibility = 2000.0;
  47729. this.previousPosition = null;
  47730. }
  47731. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47732. var _this = this;
  47733. var engine = this.camera.getEngine();
  47734. if (!this._pointerInput) {
  47735. this._pointerInput = function (p, s) {
  47736. var evt = p.event;
  47737. if (engine.isInVRExclusivePointerMode) {
  47738. return;
  47739. }
  47740. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47741. return;
  47742. }
  47743. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47744. return;
  47745. }
  47746. var srcElement = (evt.srcElement || evt.target);
  47747. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47748. try {
  47749. srcElement.setPointerCapture(evt.pointerId);
  47750. }
  47751. catch (e) {
  47752. //Nothing to do with the error. Execution will continue.
  47753. }
  47754. _this.previousPosition = {
  47755. x: evt.clientX,
  47756. y: evt.clientY
  47757. };
  47758. if (!noPreventDefault) {
  47759. evt.preventDefault();
  47760. element.focus();
  47761. }
  47762. }
  47763. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47764. try {
  47765. srcElement.releasePointerCapture(evt.pointerId);
  47766. }
  47767. catch (e) {
  47768. //Nothing to do with the error.
  47769. }
  47770. _this.previousPosition = null;
  47771. if (!noPreventDefault) {
  47772. evt.preventDefault();
  47773. }
  47774. }
  47775. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47776. if (!_this.previousPosition || engine.isPointerLock) {
  47777. return;
  47778. }
  47779. var offsetX = evt.clientX - _this.previousPosition.x;
  47780. if (_this.camera.getScene().useRightHandedSystem)
  47781. offsetX *= -1;
  47782. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47783. offsetX *= -1;
  47784. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47785. var offsetY = evt.clientY - _this.previousPosition.y;
  47786. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47787. _this.previousPosition = {
  47788. x: evt.clientX,
  47789. y: evt.clientY
  47790. };
  47791. if (!noPreventDefault) {
  47792. evt.preventDefault();
  47793. }
  47794. }
  47795. };
  47796. }
  47797. this._onMouseMove = function (evt) {
  47798. if (!engine.isPointerLock) {
  47799. return;
  47800. }
  47801. if (engine.isInVRExclusivePointerMode) {
  47802. return;
  47803. }
  47804. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47805. if (_this.camera.getScene().useRightHandedSystem)
  47806. offsetX *= -1;
  47807. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47808. offsetX *= -1;
  47809. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47810. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47811. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47812. _this.previousPosition = null;
  47813. if (!noPreventDefault) {
  47814. evt.preventDefault();
  47815. }
  47816. };
  47817. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47818. element.addEventListener("mousemove", this._onMouseMove, false);
  47819. };
  47820. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47821. if (this._observer && element) {
  47822. this.camera.getScene().onPointerObservable.remove(this._observer);
  47823. if (this._onMouseMove) {
  47824. element.removeEventListener("mousemove", this._onMouseMove);
  47825. }
  47826. this._observer = null;
  47827. this._onMouseMove = null;
  47828. this.previousPosition = null;
  47829. }
  47830. };
  47831. FreeCameraMouseInput.prototype.getClassName = function () {
  47832. return "FreeCameraMouseInput";
  47833. };
  47834. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47835. return "mouse";
  47836. };
  47837. __decorate([
  47838. BABYLON.serialize()
  47839. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47840. __decorate([
  47841. BABYLON.serialize()
  47842. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47843. return FreeCameraMouseInput;
  47844. }());
  47845. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47846. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47847. })(BABYLON || (BABYLON = {}));
  47848. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47849. var BABYLON;
  47850. (function (BABYLON) {
  47851. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47852. function FreeCameraKeyboardMoveInput() {
  47853. this._keys = new Array();
  47854. this.keysUp = [38];
  47855. this.keysDown = [40];
  47856. this.keysLeft = [37];
  47857. this.keysRight = [39];
  47858. }
  47859. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47860. var _this = this;
  47861. if (this._onCanvasBlurObserver) {
  47862. return;
  47863. }
  47864. this._scene = this.camera.getScene();
  47865. this._engine = this._scene.getEngine();
  47866. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47867. _this._keys = [];
  47868. });
  47869. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47870. var evt = info.event;
  47871. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47872. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47873. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47874. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47875. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47876. var index = _this._keys.indexOf(evt.keyCode);
  47877. if (index === -1) {
  47878. _this._keys.push(evt.keyCode);
  47879. }
  47880. if (!noPreventDefault) {
  47881. evt.preventDefault();
  47882. }
  47883. }
  47884. }
  47885. else {
  47886. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47887. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47888. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47889. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47890. var index = _this._keys.indexOf(evt.keyCode);
  47891. if (index >= 0) {
  47892. _this._keys.splice(index, 1);
  47893. }
  47894. if (!noPreventDefault) {
  47895. evt.preventDefault();
  47896. }
  47897. }
  47898. }
  47899. });
  47900. };
  47901. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47902. if (this._scene) {
  47903. if (this._onKeyboardObserver) {
  47904. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47905. }
  47906. if (this._onCanvasBlurObserver) {
  47907. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47908. }
  47909. this._onKeyboardObserver = null;
  47910. this._onCanvasBlurObserver = null;
  47911. }
  47912. this._keys = [];
  47913. };
  47914. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47915. if (this._onKeyboardObserver) {
  47916. var camera = this.camera;
  47917. // Keyboard
  47918. for (var index = 0; index < this._keys.length; index++) {
  47919. var keyCode = this._keys[index];
  47920. var speed = camera._computeLocalCameraSpeed();
  47921. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47922. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47923. }
  47924. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47925. camera._localDirection.copyFromFloats(0, 0, speed);
  47926. }
  47927. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47928. camera._localDirection.copyFromFloats(speed, 0, 0);
  47929. }
  47930. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47931. camera._localDirection.copyFromFloats(0, 0, -speed);
  47932. }
  47933. if (camera.getScene().useRightHandedSystem) {
  47934. camera._localDirection.z *= -1;
  47935. }
  47936. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47937. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47938. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47939. }
  47940. }
  47941. };
  47942. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47943. return "FreeCameraKeyboardMoveInput";
  47944. };
  47945. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47946. this._keys = [];
  47947. };
  47948. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47949. return "keyboard";
  47950. };
  47951. __decorate([
  47952. BABYLON.serialize()
  47953. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47954. __decorate([
  47955. BABYLON.serialize()
  47956. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47957. __decorate([
  47958. BABYLON.serialize()
  47959. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47963. return FreeCameraKeyboardMoveInput;
  47964. }());
  47965. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47966. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47967. })(BABYLON || (BABYLON = {}));
  47968. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47969. var BABYLON;
  47970. (function (BABYLON) {
  47971. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47972. __extends(FreeCameraInputsManager, _super);
  47973. function FreeCameraInputsManager(camera) {
  47974. return _super.call(this, camera) || this;
  47975. }
  47976. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47977. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47978. return this;
  47979. };
  47980. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47981. if (touchEnabled === void 0) { touchEnabled = true; }
  47982. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47983. return this;
  47984. };
  47985. FreeCameraInputsManager.prototype.addGamepad = function () {
  47986. this.add(new BABYLON.FreeCameraGamepadInput());
  47987. return this;
  47988. };
  47989. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47990. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47991. return this;
  47992. };
  47993. FreeCameraInputsManager.prototype.addTouch = function () {
  47994. this.add(new BABYLON.FreeCameraTouchInput());
  47995. return this;
  47996. };
  47997. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47998. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47999. return this;
  48000. };
  48001. return FreeCameraInputsManager;
  48002. }(BABYLON.CameraInputsManager));
  48003. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48004. })(BABYLON || (BABYLON = {}));
  48005. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48006. var BABYLON;
  48007. (function (BABYLON) {
  48008. var FreeCamera = /** @class */ (function (_super) {
  48009. __extends(FreeCamera, _super);
  48010. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48011. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48012. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48013. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48014. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48015. _this.checkCollisions = false;
  48016. _this.applyGravity = false;
  48017. _this._needMoveForGravity = false;
  48018. _this._oldPosition = BABYLON.Vector3.Zero();
  48019. _this._diffPosition = BABYLON.Vector3.Zero();
  48020. _this._newPosition = BABYLON.Vector3.Zero();
  48021. // Collisions
  48022. _this._collisionMask = -1;
  48023. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48024. if (collidedMesh === void 0) { collidedMesh = null; }
  48025. //TODO move this to the collision coordinator!
  48026. if (_this.getScene().workerCollisions)
  48027. newPosition.multiplyInPlace(_this._collider._radius);
  48028. var updatePosition = function (newPos) {
  48029. _this._newPosition.copyFrom(newPos);
  48030. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48031. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48032. _this.position.addInPlace(_this._diffPosition);
  48033. if (_this.onCollide && collidedMesh) {
  48034. _this.onCollide(collidedMesh);
  48035. }
  48036. }
  48037. };
  48038. updatePosition(newPosition);
  48039. };
  48040. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48041. _this.inputs.addKeyboard().addMouse();
  48042. return _this;
  48043. }
  48044. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48045. //-- begin properties for backward compatibility for inputs
  48046. /**
  48047. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48048. * Higher values reduce sensitivity.
  48049. */
  48050. get: function () {
  48051. var mouse = this.inputs.attached["mouse"];
  48052. if (mouse)
  48053. return mouse.angularSensibility;
  48054. return 0;
  48055. },
  48056. /**
  48057. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48058. * Higher values reduce sensitivity.
  48059. */
  48060. set: function (value) {
  48061. var mouse = this.inputs.attached["mouse"];
  48062. if (mouse)
  48063. mouse.angularSensibility = value;
  48064. },
  48065. enumerable: true,
  48066. configurable: true
  48067. });
  48068. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48069. get: function () {
  48070. var keyboard = this.inputs.attached["keyboard"];
  48071. if (keyboard)
  48072. return keyboard.keysUp;
  48073. return [];
  48074. },
  48075. set: function (value) {
  48076. var keyboard = this.inputs.attached["keyboard"];
  48077. if (keyboard)
  48078. keyboard.keysUp = value;
  48079. },
  48080. enumerable: true,
  48081. configurable: true
  48082. });
  48083. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48084. get: function () {
  48085. var keyboard = this.inputs.attached["keyboard"];
  48086. if (keyboard)
  48087. return keyboard.keysDown;
  48088. return [];
  48089. },
  48090. set: function (value) {
  48091. var keyboard = this.inputs.attached["keyboard"];
  48092. if (keyboard)
  48093. keyboard.keysDown = value;
  48094. },
  48095. enumerable: true,
  48096. configurable: true
  48097. });
  48098. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48099. get: function () {
  48100. var keyboard = this.inputs.attached["keyboard"];
  48101. if (keyboard)
  48102. return keyboard.keysLeft;
  48103. return [];
  48104. },
  48105. set: function (value) {
  48106. var keyboard = this.inputs.attached["keyboard"];
  48107. if (keyboard)
  48108. keyboard.keysLeft = value;
  48109. },
  48110. enumerable: true,
  48111. configurable: true
  48112. });
  48113. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48114. get: function () {
  48115. var keyboard = this.inputs.attached["keyboard"];
  48116. if (keyboard)
  48117. return keyboard.keysRight;
  48118. return [];
  48119. },
  48120. set: function (value) {
  48121. var keyboard = this.inputs.attached["keyboard"];
  48122. if (keyboard)
  48123. keyboard.keysRight = value;
  48124. },
  48125. enumerable: true,
  48126. configurable: true
  48127. });
  48128. // Controls
  48129. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48130. this.inputs.attachElement(element, noPreventDefault);
  48131. };
  48132. FreeCamera.prototype.detachControl = function (element) {
  48133. this.inputs.detachElement(element);
  48134. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48135. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48136. };
  48137. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48138. get: function () {
  48139. return this._collisionMask;
  48140. },
  48141. set: function (mask) {
  48142. this._collisionMask = !isNaN(mask) ? mask : -1;
  48143. },
  48144. enumerable: true,
  48145. configurable: true
  48146. });
  48147. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48148. var globalPosition;
  48149. if (this.parent) {
  48150. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48151. }
  48152. else {
  48153. globalPosition = this.position;
  48154. }
  48155. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48156. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48157. if (!this._collider) {
  48158. this._collider = new BABYLON.Collider();
  48159. }
  48160. this._collider._radius = this.ellipsoid;
  48161. this._collider.collisionMask = this._collisionMask;
  48162. //no need for clone, as long as gravity is not on.
  48163. var actualDisplacement = displacement;
  48164. //add gravity to the direction to prevent the dual-collision checking
  48165. if (this.applyGravity) {
  48166. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48167. actualDisplacement = displacement.add(this.getScene().gravity);
  48168. }
  48169. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48170. };
  48171. FreeCamera.prototype._checkInputs = function () {
  48172. if (!this._localDirection) {
  48173. this._localDirection = BABYLON.Vector3.Zero();
  48174. this._transformedDirection = BABYLON.Vector3.Zero();
  48175. }
  48176. this.inputs.checkInputs();
  48177. _super.prototype._checkInputs.call(this);
  48178. };
  48179. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48180. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48181. };
  48182. FreeCamera.prototype._updatePosition = function () {
  48183. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48184. this._collideWithWorld(this.cameraDirection);
  48185. }
  48186. else {
  48187. _super.prototype._updatePosition.call(this);
  48188. }
  48189. };
  48190. FreeCamera.prototype.dispose = function () {
  48191. this.inputs.clear();
  48192. _super.prototype.dispose.call(this);
  48193. };
  48194. FreeCamera.prototype.getClassName = function () {
  48195. return "FreeCamera";
  48196. };
  48197. __decorate([
  48198. BABYLON.serializeAsVector3()
  48199. ], FreeCamera.prototype, "ellipsoid", void 0);
  48200. __decorate([
  48201. BABYLON.serializeAsVector3()
  48202. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], FreeCamera.prototype, "checkCollisions", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], FreeCamera.prototype, "applyGravity", void 0);
  48209. return FreeCamera;
  48210. }(BABYLON.TargetCamera));
  48211. BABYLON.FreeCamera = FreeCamera;
  48212. })(BABYLON || (BABYLON = {}));
  48213. //# sourceMappingURL=babylon.freeCamera.js.map
  48214. var BABYLON;
  48215. (function (BABYLON) {
  48216. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48217. function ArcRotateCameraKeyboardMoveInput() {
  48218. this._keys = new Array();
  48219. this.keysUp = [38];
  48220. this.keysDown = [40];
  48221. this.keysLeft = [37];
  48222. this.keysRight = [39];
  48223. this.keysReset = [220];
  48224. this.panningSensibility = 50.0;
  48225. this.zoomingSensibility = 25.0;
  48226. this.useAltToZoom = true;
  48227. }
  48228. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48229. var _this = this;
  48230. if (this._onCanvasBlurObserver) {
  48231. return;
  48232. }
  48233. this._scene = this.camera.getScene();
  48234. this._engine = this._scene.getEngine();
  48235. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48236. _this._keys = [];
  48237. });
  48238. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48239. var evt = info.event;
  48240. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48241. _this._ctrlPressed = evt.ctrlKey;
  48242. _this._altPressed = evt.altKey;
  48243. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48244. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48245. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48246. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48247. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48248. var index = _this._keys.indexOf(evt.keyCode);
  48249. if (index === -1) {
  48250. _this._keys.push(evt.keyCode);
  48251. }
  48252. if (evt.preventDefault) {
  48253. if (!noPreventDefault) {
  48254. evt.preventDefault();
  48255. }
  48256. }
  48257. }
  48258. }
  48259. else {
  48260. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48261. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48262. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48263. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48264. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48265. var index = _this._keys.indexOf(evt.keyCode);
  48266. if (index >= 0) {
  48267. _this._keys.splice(index, 1);
  48268. }
  48269. if (evt.preventDefault) {
  48270. if (!noPreventDefault) {
  48271. evt.preventDefault();
  48272. }
  48273. }
  48274. }
  48275. }
  48276. });
  48277. };
  48278. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48279. if (this._scene) {
  48280. if (this._onKeyboardObserver) {
  48281. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48282. }
  48283. if (this._onCanvasBlurObserver) {
  48284. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48285. }
  48286. this._onKeyboardObserver = null;
  48287. this._onCanvasBlurObserver = null;
  48288. }
  48289. this._keys = [];
  48290. };
  48291. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48292. if (this._onKeyboardObserver) {
  48293. var camera = this.camera;
  48294. for (var index = 0; index < this._keys.length; index++) {
  48295. var keyCode = this._keys[index];
  48296. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48297. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48298. camera.inertialPanningX -= 1 / this.panningSensibility;
  48299. }
  48300. else {
  48301. camera.inertialAlphaOffset -= 0.01;
  48302. }
  48303. }
  48304. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48305. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48306. camera.inertialPanningY += 1 / this.panningSensibility;
  48307. }
  48308. else if (this._altPressed && this.useAltToZoom) {
  48309. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48310. }
  48311. else {
  48312. camera.inertialBetaOffset -= 0.01;
  48313. }
  48314. }
  48315. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48316. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48317. camera.inertialPanningX += 1 / this.panningSensibility;
  48318. }
  48319. else {
  48320. camera.inertialAlphaOffset += 0.01;
  48321. }
  48322. }
  48323. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48324. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48325. camera.inertialPanningY -= 1 / this.panningSensibility;
  48326. }
  48327. else if (this._altPressed && this.useAltToZoom) {
  48328. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48329. }
  48330. else {
  48331. camera.inertialBetaOffset += 0.01;
  48332. }
  48333. }
  48334. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48335. camera.restoreState();
  48336. }
  48337. }
  48338. }
  48339. };
  48340. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48341. return "ArcRotateCameraKeyboardMoveInput";
  48342. };
  48343. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48344. return "keyboard";
  48345. };
  48346. __decorate([
  48347. BABYLON.serialize()
  48348. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48349. __decorate([
  48350. BABYLON.serialize()
  48351. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48352. __decorate([
  48353. BABYLON.serialize()
  48354. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48358. __decorate([
  48359. BABYLON.serialize()
  48360. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48361. __decorate([
  48362. BABYLON.serialize()
  48363. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48370. return ArcRotateCameraKeyboardMoveInput;
  48371. }());
  48372. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48373. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48374. })(BABYLON || (BABYLON = {}));
  48375. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48376. var BABYLON;
  48377. (function (BABYLON) {
  48378. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48379. function ArcRotateCameraMouseWheelInput() {
  48380. this.wheelPrecision = 3.0;
  48381. /**
  48382. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48383. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48384. */
  48385. this.wheelDeltaPercentage = 0;
  48386. }
  48387. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48388. var _this = this;
  48389. this._wheel = function (p, s) {
  48390. //sanity check - this should be a PointerWheel event.
  48391. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48392. return;
  48393. var event = p.event;
  48394. var delta = 0;
  48395. if (event.wheelDelta) {
  48396. if (_this.wheelDeltaPercentage) {
  48397. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48398. if (event.wheelDelta > 0) {
  48399. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48400. }
  48401. else {
  48402. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48403. }
  48404. }
  48405. else {
  48406. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48407. }
  48408. }
  48409. else if (event.detail) {
  48410. delta = -event.detail / _this.wheelPrecision;
  48411. }
  48412. if (delta)
  48413. _this.camera.inertialRadiusOffset += delta;
  48414. if (event.preventDefault) {
  48415. if (!noPreventDefault) {
  48416. event.preventDefault();
  48417. }
  48418. }
  48419. };
  48420. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48421. };
  48422. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48423. if (this._observer && element) {
  48424. this.camera.getScene().onPointerObservable.remove(this._observer);
  48425. this._observer = null;
  48426. this._wheel = null;
  48427. }
  48428. };
  48429. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48430. return "ArcRotateCameraMouseWheelInput";
  48431. };
  48432. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48433. return "mousewheel";
  48434. };
  48435. __decorate([
  48436. BABYLON.serialize()
  48437. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48438. __decorate([
  48439. BABYLON.serialize()
  48440. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48441. return ArcRotateCameraMouseWheelInput;
  48442. }());
  48443. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48444. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48445. })(BABYLON || (BABYLON = {}));
  48446. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48447. var BABYLON;
  48448. (function (BABYLON) {
  48449. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48450. function ArcRotateCameraPointersInput() {
  48451. this.buttons = [0, 1, 2];
  48452. this.angularSensibilityX = 1000.0;
  48453. this.angularSensibilityY = 1000.0;
  48454. this.pinchPrecision = 12.0;
  48455. /**
  48456. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48457. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48458. */
  48459. this.pinchDeltaPercentage = 0;
  48460. this.panningSensibility = 1000.0;
  48461. this.multiTouchPanning = true;
  48462. this.multiTouchPanAndZoom = true;
  48463. this._isPanClick = false;
  48464. this.pinchInwards = true;
  48465. }
  48466. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48467. var _this = this;
  48468. var engine = this.camera.getEngine();
  48469. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48470. var pointA = null;
  48471. var pointB = null;
  48472. var previousPinchSquaredDistance = 0;
  48473. var initialDistance = 0;
  48474. var twoFingerActivityCount = 0;
  48475. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48476. this._pointerInput = function (p, s) {
  48477. var evt = p.event;
  48478. var isTouch = p.event.pointerType === "touch";
  48479. if (engine.isInVRExclusivePointerMode) {
  48480. return;
  48481. }
  48482. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48483. return;
  48484. }
  48485. var srcElement = (evt.srcElement || evt.target);
  48486. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48487. try {
  48488. srcElement.setPointerCapture(evt.pointerId);
  48489. }
  48490. catch (e) {
  48491. //Nothing to do with the error. Execution will continue.
  48492. }
  48493. // Manage panning with pan button click
  48494. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48495. // manage pointers
  48496. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48497. if (pointA === null) {
  48498. pointA = cacheSoloPointer;
  48499. }
  48500. else if (pointB === null) {
  48501. pointB = cacheSoloPointer;
  48502. }
  48503. if (!noPreventDefault) {
  48504. evt.preventDefault();
  48505. element.focus();
  48506. }
  48507. }
  48508. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48509. _this.camera.restoreState();
  48510. }
  48511. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48512. try {
  48513. srcElement.releasePointerCapture(evt.pointerId);
  48514. }
  48515. catch (e) {
  48516. //Nothing to do with the error.
  48517. }
  48518. cacheSoloPointer = null;
  48519. previousPinchSquaredDistance = 0;
  48520. previousMultiTouchPanPosition.isPaning = false;
  48521. previousMultiTouchPanPosition.isPinching = false;
  48522. twoFingerActivityCount = 0;
  48523. initialDistance = 0;
  48524. if (!isTouch) {
  48525. pointB = null; // Mouse and pen are mono pointer
  48526. }
  48527. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48528. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48529. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48530. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48531. if (engine._badOS) {
  48532. pointA = pointB = null;
  48533. }
  48534. else {
  48535. //only remove the impacted pointer in case of multitouch allowing on most
  48536. //platforms switching from rotate to zoom and pan seamlessly.
  48537. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48538. pointA = pointB;
  48539. pointB = null;
  48540. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48541. }
  48542. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48543. pointB = null;
  48544. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48545. }
  48546. else {
  48547. pointA = pointB = null;
  48548. }
  48549. }
  48550. if (!noPreventDefault) {
  48551. evt.preventDefault();
  48552. }
  48553. }
  48554. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48555. if (!noPreventDefault) {
  48556. evt.preventDefault();
  48557. }
  48558. // One button down
  48559. if (pointA && pointB === null && cacheSoloPointer) {
  48560. if (_this.panningSensibility !== 0 &&
  48561. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48562. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48563. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48564. }
  48565. else {
  48566. var offsetX = evt.clientX - cacheSoloPointer.x;
  48567. var offsetY = evt.clientY - cacheSoloPointer.y;
  48568. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48569. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48570. }
  48571. cacheSoloPointer.x = evt.clientX;
  48572. cacheSoloPointer.y = evt.clientY;
  48573. }
  48574. // Two buttons down: pinch/pan
  48575. else if (pointA && pointB) {
  48576. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48577. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48578. ed.x = evt.clientX;
  48579. ed.y = evt.clientY;
  48580. var direction = _this.pinchInwards ? 1 : -1;
  48581. var distX = pointA.x - pointB.x;
  48582. var distY = pointA.y - pointB.y;
  48583. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48584. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48585. if (previousPinchSquaredDistance === 0) {
  48586. initialDistance = pinchDistance;
  48587. previousPinchSquaredDistance = pinchSquaredDistance;
  48588. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48589. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48590. return;
  48591. }
  48592. if (_this.multiTouchPanAndZoom) {
  48593. if (_this.pinchDeltaPercentage) {
  48594. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48595. }
  48596. else {
  48597. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48598. (_this.pinchPrecision *
  48599. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48600. direction);
  48601. }
  48602. if (_this.panningSensibility !== 0) {
  48603. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48604. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48605. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48606. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48607. previousMultiTouchPanPosition.x = pointersCenterX;
  48608. previousMultiTouchPanPosition.y = pointersCenterY;
  48609. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48610. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48611. }
  48612. }
  48613. else {
  48614. twoFingerActivityCount++;
  48615. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48616. if (_this.pinchDeltaPercentage) {
  48617. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48618. }
  48619. else {
  48620. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48621. (_this.pinchPrecision *
  48622. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48623. direction);
  48624. }
  48625. previousMultiTouchPanPosition.isPaning = false;
  48626. previousMultiTouchPanPosition.isPinching = true;
  48627. }
  48628. else {
  48629. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48630. if (!previousMultiTouchPanPosition.isPaning) {
  48631. previousMultiTouchPanPosition.isPaning = true;
  48632. previousMultiTouchPanPosition.isPinching = false;
  48633. previousMultiTouchPanPosition.x = ed.x;
  48634. previousMultiTouchPanPosition.y = ed.y;
  48635. return;
  48636. }
  48637. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48638. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48639. }
  48640. }
  48641. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48642. previousMultiTouchPanPosition.x = ed.x;
  48643. previousMultiTouchPanPosition.y = ed.y;
  48644. }
  48645. }
  48646. previousPinchSquaredDistance = pinchSquaredDistance;
  48647. }
  48648. }
  48649. };
  48650. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48651. this._onContextMenu = function (evt) {
  48652. evt.preventDefault();
  48653. };
  48654. if (!this.camera._useCtrlForPanning) {
  48655. element.addEventListener("contextmenu", this._onContextMenu, false);
  48656. }
  48657. this._onLostFocus = function () {
  48658. //this._keys = [];
  48659. pointA = pointB = null;
  48660. previousPinchSquaredDistance = 0;
  48661. previousMultiTouchPanPosition.isPaning = false;
  48662. previousMultiTouchPanPosition.isPinching = false;
  48663. twoFingerActivityCount = 0;
  48664. cacheSoloPointer = null;
  48665. initialDistance = 0;
  48666. };
  48667. this._onMouseMove = function (evt) {
  48668. if (!engine.isPointerLock) {
  48669. return;
  48670. }
  48671. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48672. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48673. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48674. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48675. if (!noPreventDefault) {
  48676. evt.preventDefault();
  48677. }
  48678. };
  48679. this._onGestureStart = function (e) {
  48680. if (window.MSGesture === undefined) {
  48681. return;
  48682. }
  48683. if (!_this._MSGestureHandler) {
  48684. _this._MSGestureHandler = new MSGesture();
  48685. _this._MSGestureHandler.target = element;
  48686. }
  48687. _this._MSGestureHandler.addPointer(e.pointerId);
  48688. };
  48689. this._onGesture = function (e) {
  48690. _this.camera.radius *= e.scale;
  48691. if (e.preventDefault) {
  48692. if (!noPreventDefault) {
  48693. e.stopPropagation();
  48694. e.preventDefault();
  48695. }
  48696. }
  48697. };
  48698. element.addEventListener("mousemove", this._onMouseMove, false);
  48699. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48700. element.addEventListener("MSGestureChange", this._onGesture, false);
  48701. BABYLON.Tools.RegisterTopRootEvents([
  48702. { name: "blur", handler: this._onLostFocus }
  48703. ]);
  48704. };
  48705. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48706. if (this._onLostFocus) {
  48707. BABYLON.Tools.UnregisterTopRootEvents([
  48708. { name: "blur", handler: this._onLostFocus }
  48709. ]);
  48710. }
  48711. if (element && this._observer) {
  48712. this.camera.getScene().onPointerObservable.remove(this._observer);
  48713. this._observer = null;
  48714. if (this._onContextMenu) {
  48715. element.removeEventListener("contextmenu", this._onContextMenu);
  48716. }
  48717. if (this._onMouseMove) {
  48718. element.removeEventListener("mousemove", this._onMouseMove);
  48719. }
  48720. if (this._onGestureStart) {
  48721. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48722. }
  48723. if (this._onGesture) {
  48724. element.removeEventListener("MSGestureChange", this._onGesture);
  48725. }
  48726. this._isPanClick = false;
  48727. this.pinchInwards = true;
  48728. this._onMouseMove = null;
  48729. this._onGestureStart = null;
  48730. this._onGesture = null;
  48731. this._MSGestureHandler = null;
  48732. this._onLostFocus = null;
  48733. this._onContextMenu = null;
  48734. }
  48735. };
  48736. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48737. return "ArcRotateCameraPointersInput";
  48738. };
  48739. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48740. return "pointers";
  48741. };
  48742. __decorate([
  48743. BABYLON.serialize()
  48744. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48745. __decorate([
  48746. BABYLON.serialize()
  48747. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48751. __decorate([
  48752. BABYLON.serialize()
  48753. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48754. __decorate([
  48755. BABYLON.serialize()
  48756. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48757. __decorate([
  48758. BABYLON.serialize()
  48759. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48766. return ArcRotateCameraPointersInput;
  48767. }());
  48768. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48769. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48770. })(BABYLON || (BABYLON = {}));
  48771. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48772. var BABYLON;
  48773. (function (BABYLON) {
  48774. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48775. __extends(ArcRotateCameraInputsManager, _super);
  48776. function ArcRotateCameraInputsManager(camera) {
  48777. return _super.call(this, camera) || this;
  48778. }
  48779. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48780. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48781. return this;
  48782. };
  48783. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48784. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48785. return this;
  48786. };
  48787. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48788. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48789. return this;
  48790. };
  48791. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48792. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48793. return this;
  48794. };
  48795. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48796. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48797. return this;
  48798. };
  48799. return ArcRotateCameraInputsManager;
  48800. }(BABYLON.CameraInputsManager));
  48801. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48802. })(BABYLON || (BABYLON = {}));
  48803. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48804. var BABYLON;
  48805. (function (BABYLON) {
  48806. var ArcRotateCamera = /** @class */ (function (_super) {
  48807. __extends(ArcRotateCamera, _super);
  48808. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48809. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48810. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48811. _this.inertialAlphaOffset = 0;
  48812. _this.inertialBetaOffset = 0;
  48813. _this.inertialRadiusOffset = 0;
  48814. _this.lowerAlphaLimit = null;
  48815. _this.upperAlphaLimit = null;
  48816. _this.lowerBetaLimit = 0.01;
  48817. _this.upperBetaLimit = Math.PI;
  48818. _this.lowerRadiusLimit = null;
  48819. _this.upperRadiusLimit = null;
  48820. _this.inertialPanningX = 0;
  48821. _this.inertialPanningY = 0;
  48822. _this.pinchToPanMaxDistance = 20;
  48823. _this.panningDistanceLimit = null;
  48824. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48825. _this.panningInertia = 0.9;
  48826. //-- end properties for backward compatibility for inputs
  48827. _this.zoomOnFactor = 1;
  48828. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48829. _this.allowUpsideDown = true;
  48830. _this._viewMatrix = new BABYLON.Matrix();
  48831. // Panning
  48832. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48833. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48834. _this.checkCollisions = false;
  48835. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48836. _this._previousPosition = BABYLON.Vector3.Zero();
  48837. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48838. _this._newPosition = BABYLON.Vector3.Zero();
  48839. _this._computationVector = BABYLON.Vector3.Zero();
  48840. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48841. if (collidedMesh === void 0) { collidedMesh = null; }
  48842. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48843. newPosition.multiplyInPlace(_this._collider._radius);
  48844. }
  48845. if (!collidedMesh) {
  48846. _this._previousPosition.copyFrom(_this.position);
  48847. }
  48848. else {
  48849. _this.setPosition(newPosition);
  48850. if (_this.onCollide) {
  48851. _this.onCollide(collidedMesh);
  48852. }
  48853. }
  48854. // Recompute because of constraints
  48855. var cosa = Math.cos(_this.alpha);
  48856. var sina = Math.sin(_this.alpha);
  48857. var cosb = Math.cos(_this.beta);
  48858. var sinb = Math.sin(_this.beta);
  48859. if (sinb === 0) {
  48860. sinb = 0.0001;
  48861. }
  48862. var target = _this._getTargetPosition();
  48863. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48864. target.addToRef(_this._computationVector, _this._newPosition);
  48865. _this.position.copyFrom(_this._newPosition);
  48866. var up = _this.upVector;
  48867. if (_this.allowUpsideDown && _this.beta < 0) {
  48868. up = up.clone();
  48869. up = up.negate();
  48870. }
  48871. _this._computeViewMatrix(_this.position, target, up);
  48872. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48873. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48874. _this._collisionTriggered = false;
  48875. };
  48876. _this._target = BABYLON.Vector3.Zero();
  48877. if (target) {
  48878. _this.setTarget(target);
  48879. }
  48880. _this.alpha = alpha;
  48881. _this.beta = beta;
  48882. _this.radius = radius;
  48883. _this.getViewMatrix();
  48884. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48885. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48886. return _this;
  48887. }
  48888. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48889. get: function () {
  48890. return this._target;
  48891. },
  48892. set: function (value) {
  48893. this.setTarget(value);
  48894. },
  48895. enumerable: true,
  48896. configurable: true
  48897. });
  48898. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48899. //-- begin properties for backward compatibility for inputs
  48900. get: function () {
  48901. var pointers = this.inputs.attached["pointers"];
  48902. if (pointers)
  48903. return pointers.angularSensibilityX;
  48904. return 0;
  48905. },
  48906. set: function (value) {
  48907. var pointers = this.inputs.attached["pointers"];
  48908. if (pointers) {
  48909. pointers.angularSensibilityX = value;
  48910. }
  48911. },
  48912. enumerable: true,
  48913. configurable: true
  48914. });
  48915. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48916. get: function () {
  48917. var pointers = this.inputs.attached["pointers"];
  48918. if (pointers)
  48919. return pointers.angularSensibilityY;
  48920. return 0;
  48921. },
  48922. set: function (value) {
  48923. var pointers = this.inputs.attached["pointers"];
  48924. if (pointers) {
  48925. pointers.angularSensibilityY = value;
  48926. }
  48927. },
  48928. enumerable: true,
  48929. configurable: true
  48930. });
  48931. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48932. get: function () {
  48933. var pointers = this.inputs.attached["pointers"];
  48934. if (pointers)
  48935. return pointers.pinchPrecision;
  48936. return 0;
  48937. },
  48938. set: function (value) {
  48939. var pointers = this.inputs.attached["pointers"];
  48940. if (pointers) {
  48941. pointers.pinchPrecision = value;
  48942. }
  48943. },
  48944. enumerable: true,
  48945. configurable: true
  48946. });
  48947. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48948. get: function () {
  48949. var pointers = this.inputs.attached["pointers"];
  48950. if (pointers)
  48951. return pointers.pinchDeltaPercentage;
  48952. return 0;
  48953. },
  48954. set: function (value) {
  48955. var pointers = this.inputs.attached["pointers"];
  48956. if (pointers) {
  48957. pointers.pinchDeltaPercentage = value;
  48958. }
  48959. },
  48960. enumerable: true,
  48961. configurable: true
  48962. });
  48963. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48964. get: function () {
  48965. var pointers = this.inputs.attached["pointers"];
  48966. if (pointers)
  48967. return pointers.panningSensibility;
  48968. return 0;
  48969. },
  48970. set: function (value) {
  48971. var pointers = this.inputs.attached["pointers"];
  48972. if (pointers) {
  48973. pointers.panningSensibility = value;
  48974. }
  48975. },
  48976. enumerable: true,
  48977. configurable: true
  48978. });
  48979. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48980. get: function () {
  48981. var keyboard = this.inputs.attached["keyboard"];
  48982. if (keyboard)
  48983. return keyboard.keysUp;
  48984. return [];
  48985. },
  48986. set: function (value) {
  48987. var keyboard = this.inputs.attached["keyboard"];
  48988. if (keyboard)
  48989. keyboard.keysUp = value;
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48995. get: function () {
  48996. var keyboard = this.inputs.attached["keyboard"];
  48997. if (keyboard)
  48998. return keyboard.keysDown;
  48999. return [];
  49000. },
  49001. set: function (value) {
  49002. var keyboard = this.inputs.attached["keyboard"];
  49003. if (keyboard)
  49004. keyboard.keysDown = value;
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49010. get: function () {
  49011. var keyboard = this.inputs.attached["keyboard"];
  49012. if (keyboard)
  49013. return keyboard.keysLeft;
  49014. return [];
  49015. },
  49016. set: function (value) {
  49017. var keyboard = this.inputs.attached["keyboard"];
  49018. if (keyboard)
  49019. keyboard.keysLeft = value;
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49025. get: function () {
  49026. var keyboard = this.inputs.attached["keyboard"];
  49027. if (keyboard)
  49028. return keyboard.keysRight;
  49029. return [];
  49030. },
  49031. set: function (value) {
  49032. var keyboard = this.inputs.attached["keyboard"];
  49033. if (keyboard)
  49034. keyboard.keysRight = value;
  49035. },
  49036. enumerable: true,
  49037. configurable: true
  49038. });
  49039. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49040. get: function () {
  49041. var mousewheel = this.inputs.attached["mousewheel"];
  49042. if (mousewheel)
  49043. return mousewheel.wheelPrecision;
  49044. return 0;
  49045. },
  49046. set: function (value) {
  49047. var mousewheel = this.inputs.attached["mousewheel"];
  49048. if (mousewheel)
  49049. mousewheel.wheelPrecision = value;
  49050. },
  49051. enumerable: true,
  49052. configurable: true
  49053. });
  49054. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49055. get: function () {
  49056. var mousewheel = this.inputs.attached["mousewheel"];
  49057. if (mousewheel)
  49058. return mousewheel.wheelDeltaPercentage;
  49059. return 0;
  49060. },
  49061. set: function (value) {
  49062. var mousewheel = this.inputs.attached["mousewheel"];
  49063. if (mousewheel)
  49064. mousewheel.wheelDeltaPercentage = value;
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49070. get: function () {
  49071. return this._bouncingBehavior;
  49072. },
  49073. enumerable: true,
  49074. configurable: true
  49075. });
  49076. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49077. get: function () {
  49078. return this._bouncingBehavior != null;
  49079. },
  49080. set: function (value) {
  49081. if (value === this.useBouncingBehavior) {
  49082. return;
  49083. }
  49084. if (value) {
  49085. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49086. this.addBehavior(this._bouncingBehavior);
  49087. }
  49088. else if (this._bouncingBehavior) {
  49089. this.removeBehavior(this._bouncingBehavior);
  49090. this._bouncingBehavior = null;
  49091. }
  49092. },
  49093. enumerable: true,
  49094. configurable: true
  49095. });
  49096. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49097. get: function () {
  49098. return this._framingBehavior;
  49099. },
  49100. enumerable: true,
  49101. configurable: true
  49102. });
  49103. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49104. get: function () {
  49105. return this._framingBehavior != null;
  49106. },
  49107. set: function (value) {
  49108. if (value === this.useFramingBehavior) {
  49109. return;
  49110. }
  49111. if (value) {
  49112. this._framingBehavior = new BABYLON.FramingBehavior();
  49113. this.addBehavior(this._framingBehavior);
  49114. }
  49115. else if (this._framingBehavior) {
  49116. this.removeBehavior(this._framingBehavior);
  49117. this._framingBehavior = null;
  49118. }
  49119. },
  49120. enumerable: true,
  49121. configurable: true
  49122. });
  49123. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49124. get: function () {
  49125. return this._autoRotationBehavior;
  49126. },
  49127. enumerable: true,
  49128. configurable: true
  49129. });
  49130. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49131. get: function () {
  49132. return this._autoRotationBehavior != null;
  49133. },
  49134. set: function (value) {
  49135. if (value === this.useAutoRotationBehavior) {
  49136. return;
  49137. }
  49138. if (value) {
  49139. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49140. this.addBehavior(this._autoRotationBehavior);
  49141. }
  49142. else if (this._autoRotationBehavior) {
  49143. this.removeBehavior(this._autoRotationBehavior);
  49144. this._autoRotationBehavior = null;
  49145. }
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. // Cache
  49151. ArcRotateCamera.prototype._initCache = function () {
  49152. _super.prototype._initCache.call(this);
  49153. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49154. this._cache.alpha = undefined;
  49155. this._cache.beta = undefined;
  49156. this._cache.radius = undefined;
  49157. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49158. };
  49159. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49160. if (!ignoreParentClass) {
  49161. _super.prototype._updateCache.call(this);
  49162. }
  49163. this._cache._target.copyFrom(this._getTargetPosition());
  49164. this._cache.alpha = this.alpha;
  49165. this._cache.beta = this.beta;
  49166. this._cache.radius = this.radius;
  49167. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49168. };
  49169. ArcRotateCamera.prototype._getTargetPosition = function () {
  49170. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49171. var pos = this._targetHost.getAbsolutePosition();
  49172. if (this._targetBoundingCenter) {
  49173. pos.addToRef(this._targetBoundingCenter, this._target);
  49174. }
  49175. else {
  49176. this._target.copyFrom(pos);
  49177. }
  49178. }
  49179. var lockedTargetPosition = this._getLockedTargetPosition();
  49180. if (lockedTargetPosition) {
  49181. return lockedTargetPosition;
  49182. }
  49183. return this._target;
  49184. };
  49185. ArcRotateCamera.prototype.storeState = function () {
  49186. this._storedAlpha = this.alpha;
  49187. this._storedBeta = this.beta;
  49188. this._storedRadius = this.radius;
  49189. this._storedTarget = this._getTargetPosition().clone();
  49190. return _super.prototype.storeState.call(this);
  49191. };
  49192. /**
  49193. * Restored camera state. You must call storeState() first
  49194. */
  49195. ArcRotateCamera.prototype._restoreStateValues = function () {
  49196. if (!_super.prototype._restoreStateValues.call(this)) {
  49197. return false;
  49198. }
  49199. this.alpha = this._storedAlpha;
  49200. this.beta = this._storedBeta;
  49201. this.radius = this._storedRadius;
  49202. this.setTarget(this._storedTarget.clone());
  49203. this.inertialAlphaOffset = 0;
  49204. this.inertialBetaOffset = 0;
  49205. this.inertialRadiusOffset = 0;
  49206. this.inertialPanningX = 0;
  49207. this.inertialPanningY = 0;
  49208. return true;
  49209. };
  49210. // Synchronized
  49211. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49212. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49213. return false;
  49214. return this._cache._target.equals(this._getTargetPosition())
  49215. && this._cache.alpha === this.alpha
  49216. && this._cache.beta === this.beta
  49217. && this._cache.radius === this.radius
  49218. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49219. };
  49220. // Methods
  49221. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49222. var _this = this;
  49223. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49224. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49225. this._useCtrlForPanning = useCtrlForPanning;
  49226. this._panningMouseButton = panningMouseButton;
  49227. this.inputs.attachElement(element, noPreventDefault);
  49228. this._reset = function () {
  49229. _this.inertialAlphaOffset = 0;
  49230. _this.inertialBetaOffset = 0;
  49231. _this.inertialRadiusOffset = 0;
  49232. _this.inertialPanningX = 0;
  49233. _this.inertialPanningY = 0;
  49234. };
  49235. };
  49236. ArcRotateCamera.prototype.detachControl = function (element) {
  49237. this.inputs.detachElement(element);
  49238. if (this._reset) {
  49239. this._reset();
  49240. }
  49241. };
  49242. ArcRotateCamera.prototype._checkInputs = function () {
  49243. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49244. if (this._collisionTriggered) {
  49245. return;
  49246. }
  49247. this.inputs.checkInputs();
  49248. // Inertia
  49249. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49250. var inertialAlphaOffset = this.inertialAlphaOffset;
  49251. if (this.beta <= 0)
  49252. inertialAlphaOffset *= -1;
  49253. if (this.getScene().useRightHandedSystem)
  49254. inertialAlphaOffset *= -1;
  49255. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49256. inertialAlphaOffset *= -1;
  49257. this.alpha += inertialAlphaOffset;
  49258. this.beta += this.inertialBetaOffset;
  49259. this.radius -= this.inertialRadiusOffset;
  49260. this.inertialAlphaOffset *= this.inertia;
  49261. this.inertialBetaOffset *= this.inertia;
  49262. this.inertialRadiusOffset *= this.inertia;
  49263. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49264. this.inertialAlphaOffset = 0;
  49265. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49266. this.inertialBetaOffset = 0;
  49267. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49268. this.inertialRadiusOffset = 0;
  49269. }
  49270. // Panning inertia
  49271. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49272. if (!this._localDirection) {
  49273. this._localDirection = BABYLON.Vector3.Zero();
  49274. this._transformedDirection = BABYLON.Vector3.Zero();
  49275. }
  49276. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49277. this._localDirection.multiplyInPlace(this.panningAxis);
  49278. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49279. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49280. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49281. if (!this.panningAxis.y) {
  49282. this._transformedDirection.y = 0;
  49283. }
  49284. if (!this._targetHost) {
  49285. if (this.panningDistanceLimit) {
  49286. this._transformedDirection.addInPlace(this._target);
  49287. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49288. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49289. this._target.copyFrom(this._transformedDirection);
  49290. }
  49291. }
  49292. else {
  49293. this._target.addInPlace(this._transformedDirection);
  49294. }
  49295. }
  49296. this.inertialPanningX *= this.panningInertia;
  49297. this.inertialPanningY *= this.panningInertia;
  49298. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49299. this.inertialPanningX = 0;
  49300. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49301. this.inertialPanningY = 0;
  49302. }
  49303. // Limits
  49304. this._checkLimits();
  49305. _super.prototype._checkInputs.call(this);
  49306. };
  49307. ArcRotateCamera.prototype._checkLimits = function () {
  49308. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49309. if (this.allowUpsideDown && this.beta > Math.PI) {
  49310. this.beta = this.beta - (2 * Math.PI);
  49311. }
  49312. }
  49313. else {
  49314. if (this.beta < this.lowerBetaLimit) {
  49315. this.beta = this.lowerBetaLimit;
  49316. }
  49317. }
  49318. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49319. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49320. this.beta = this.beta + (2 * Math.PI);
  49321. }
  49322. }
  49323. else {
  49324. if (this.beta > this.upperBetaLimit) {
  49325. this.beta = this.upperBetaLimit;
  49326. }
  49327. }
  49328. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49329. this.alpha = this.lowerAlphaLimit;
  49330. }
  49331. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49332. this.alpha = this.upperAlphaLimit;
  49333. }
  49334. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49335. this.radius = this.lowerRadiusLimit;
  49336. }
  49337. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49338. this.radius = this.upperRadiusLimit;
  49339. }
  49340. };
  49341. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49342. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49343. this.radius = this._computationVector.length();
  49344. if (this.radius === 0) {
  49345. this.radius = 0.0001; // Just to avoid division by zero
  49346. }
  49347. // Alpha
  49348. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49349. if (this._computationVector.z < 0) {
  49350. this.alpha = 2 * Math.PI - this.alpha;
  49351. }
  49352. // Beta
  49353. this.beta = Math.acos(this._computationVector.y / this.radius);
  49354. this._checkLimits();
  49355. };
  49356. ArcRotateCamera.prototype.setPosition = function (position) {
  49357. if (this.position.equals(position)) {
  49358. return;
  49359. }
  49360. this.position.copyFrom(position);
  49361. this.rebuildAnglesAndRadius();
  49362. };
  49363. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49364. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49365. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49366. if (target.getBoundingInfo) {
  49367. if (toBoundingCenter) {
  49368. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49369. }
  49370. else {
  49371. this._targetBoundingCenter = null;
  49372. }
  49373. this._targetHost = target;
  49374. this._target = this._getTargetPosition();
  49375. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49376. }
  49377. else {
  49378. var newTarget = target;
  49379. var currentTarget = this._getTargetPosition();
  49380. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49381. return;
  49382. }
  49383. this._targetHost = null;
  49384. this._target = newTarget;
  49385. this._targetBoundingCenter = null;
  49386. this.onMeshTargetChangedObservable.notifyObservers(null);
  49387. }
  49388. this.rebuildAnglesAndRadius();
  49389. };
  49390. ArcRotateCamera.prototype._getViewMatrix = function () {
  49391. // Compute
  49392. var cosa = Math.cos(this.alpha);
  49393. var sina = Math.sin(this.alpha);
  49394. var cosb = Math.cos(this.beta);
  49395. var sinb = Math.sin(this.beta);
  49396. if (sinb === 0) {
  49397. sinb = 0.0001;
  49398. }
  49399. var target = this._getTargetPosition();
  49400. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49401. target.addToRef(this._computationVector, this._newPosition);
  49402. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49403. if (!this._collider) {
  49404. this._collider = new BABYLON.Collider();
  49405. }
  49406. this._collider._radius = this.collisionRadius;
  49407. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49408. this._collisionTriggered = true;
  49409. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49410. }
  49411. else {
  49412. this.position.copyFrom(this._newPosition);
  49413. var up = this.upVector;
  49414. if (this.allowUpsideDown && sinb < 0) {
  49415. up = up.clone();
  49416. up = up.negate();
  49417. }
  49418. this._computeViewMatrix(this.position, target, up);
  49419. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49420. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49421. }
  49422. this._currentTarget = target;
  49423. return this._viewMatrix;
  49424. };
  49425. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49426. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49427. meshes = meshes || this.getScene().meshes;
  49428. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49429. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49430. this.radius = distance * this.zoomOnFactor;
  49431. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49432. };
  49433. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49434. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49435. var meshesOrMinMaxVector;
  49436. var distance;
  49437. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49438. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49439. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49440. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49441. }
  49442. else { //minMaxVector and distance
  49443. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49444. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49445. distance = minMaxVectorAndDistance.distance;
  49446. }
  49447. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49448. if (!doNotUpdateMaxZ) {
  49449. this.maxZ = distance * 2;
  49450. }
  49451. };
  49452. /**
  49453. * @override
  49454. * Override Camera.createRigCamera
  49455. */
  49456. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49457. var alphaShift = 0;
  49458. switch (this.cameraRigMode) {
  49459. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49460. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49461. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49462. case BABYLON.Camera.RIG_MODE_VR:
  49463. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49464. break;
  49465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49466. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49467. break;
  49468. }
  49469. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49470. rigCam._cameraRigParams = {};
  49471. return rigCam;
  49472. };
  49473. /**
  49474. * @override
  49475. * Override Camera._updateRigCameras
  49476. */
  49477. ArcRotateCamera.prototype._updateRigCameras = function () {
  49478. var camLeft = this._rigCameras[0];
  49479. var camRight = this._rigCameras[1];
  49480. camLeft.beta = camRight.beta = this.beta;
  49481. camLeft.radius = camRight.radius = this.radius;
  49482. switch (this.cameraRigMode) {
  49483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49484. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49485. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49486. case BABYLON.Camera.RIG_MODE_VR:
  49487. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49488. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49489. break;
  49490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49491. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49492. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49493. break;
  49494. }
  49495. _super.prototype._updateRigCameras.call(this);
  49496. };
  49497. ArcRotateCamera.prototype.dispose = function () {
  49498. this.inputs.clear();
  49499. _super.prototype.dispose.call(this);
  49500. };
  49501. ArcRotateCamera.prototype.getClassName = function () {
  49502. return "ArcRotateCamera";
  49503. };
  49504. __decorate([
  49505. BABYLON.serialize()
  49506. ], ArcRotateCamera.prototype, "alpha", void 0);
  49507. __decorate([
  49508. BABYLON.serialize()
  49509. ], ArcRotateCamera.prototype, "beta", void 0);
  49510. __decorate([
  49511. BABYLON.serialize()
  49512. ], ArcRotateCamera.prototype, "radius", void 0);
  49513. __decorate([
  49514. BABYLON.serializeAsVector3("target")
  49515. ], ArcRotateCamera.prototype, "_target", void 0);
  49516. __decorate([
  49517. BABYLON.serialize()
  49518. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49519. __decorate([
  49520. BABYLON.serialize()
  49521. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49522. __decorate([
  49523. BABYLON.serialize()
  49524. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49525. __decorate([
  49526. BABYLON.serialize()
  49527. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49528. __decorate([
  49529. BABYLON.serialize()
  49530. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49531. __decorate([
  49532. BABYLON.serialize()
  49533. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49534. __decorate([
  49535. BABYLON.serialize()
  49536. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49537. __decorate([
  49538. BABYLON.serialize()
  49539. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49540. __decorate([
  49541. BABYLON.serialize()
  49542. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49543. __decorate([
  49544. BABYLON.serialize()
  49545. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49555. __decorate([
  49556. BABYLON.serializeAsVector3()
  49557. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49564. __decorate([
  49565. BABYLON.serialize()
  49566. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49567. return ArcRotateCamera;
  49568. }(BABYLON.TargetCamera));
  49569. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49570. })(BABYLON || (BABYLON = {}));
  49571. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49572. var BABYLON;
  49573. (function (BABYLON) {
  49574. /**
  49575. * The HemisphericLight simulates the ambient environment light,
  49576. * so the passed direction is the light reflection direction, not the incoming direction.
  49577. */
  49578. var HemisphericLight = /** @class */ (function (_super) {
  49579. __extends(HemisphericLight, _super);
  49580. /**
  49581. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49582. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49583. * The HemisphericLight can't cast shadows.
  49584. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49585. * @param name The friendly name of the light
  49586. * @param direction The direction of the light reflection
  49587. * @param scene The scene the light belongs to
  49588. */
  49589. function HemisphericLight(name, direction, scene) {
  49590. var _this = _super.call(this, name, scene) || this;
  49591. /**
  49592. * The groundColor is the light in the opposite direction to the one specified during creation.
  49593. * 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.
  49594. */
  49595. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49596. _this.direction = direction || BABYLON.Vector3.Up();
  49597. return _this;
  49598. }
  49599. HemisphericLight.prototype._buildUniformLayout = function () {
  49600. this._uniformBuffer.addUniform("vLightData", 4);
  49601. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49602. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49603. this._uniformBuffer.addUniform("vLightGround", 3);
  49604. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49605. this._uniformBuffer.addUniform("depthValues", 2);
  49606. this._uniformBuffer.create();
  49607. };
  49608. /**
  49609. * Returns the string "HemisphericLight".
  49610. * @return The class name
  49611. */
  49612. HemisphericLight.prototype.getClassName = function () {
  49613. return "HemisphericLight";
  49614. };
  49615. /**
  49616. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49617. * Returns the updated direction.
  49618. * @param target The target the direction should point to
  49619. * @return The computed direction
  49620. */
  49621. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49622. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49623. return this.direction;
  49624. };
  49625. /**
  49626. * Returns the shadow generator associated to the light.
  49627. * @returns Always null for hemispheric lights because it does not support shadows.
  49628. */
  49629. HemisphericLight.prototype.getShadowGenerator = function () {
  49630. return null;
  49631. };
  49632. /**
  49633. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49634. * @param effect The effect to update
  49635. * @param lightIndex The index of the light in the effect to update
  49636. * @returns The hemispheric light
  49637. */
  49638. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49639. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49640. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49641. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49642. return this;
  49643. };
  49644. /**
  49645. * @hidden internal use only.
  49646. */
  49647. HemisphericLight.prototype._getWorldMatrix = function () {
  49648. if (!this._worldMatrix) {
  49649. this._worldMatrix = BABYLON.Matrix.Identity();
  49650. }
  49651. return this._worldMatrix;
  49652. };
  49653. /**
  49654. * Returns the integer 3.
  49655. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49656. */
  49657. HemisphericLight.prototype.getTypeID = function () {
  49658. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49659. };
  49660. __decorate([
  49661. BABYLON.serializeAsColor3()
  49662. ], HemisphericLight.prototype, "groundColor", void 0);
  49663. __decorate([
  49664. BABYLON.serializeAsVector3()
  49665. ], HemisphericLight.prototype, "direction", void 0);
  49666. return HemisphericLight;
  49667. }(BABYLON.Light));
  49668. BABYLON.HemisphericLight = HemisphericLight;
  49669. })(BABYLON || (BABYLON = {}));
  49670. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49671. var BABYLON;
  49672. (function (BABYLON) {
  49673. /**
  49674. * Base implementation IShadowLight
  49675. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49676. */
  49677. var ShadowLight = /** @class */ (function (_super) {
  49678. __extends(ShadowLight, _super);
  49679. function ShadowLight() {
  49680. var _this = _super !== null && _super.apply(this, arguments) || this;
  49681. _this._needProjectionMatrixCompute = true;
  49682. return _this;
  49683. }
  49684. ShadowLight.prototype._setPosition = function (value) {
  49685. this._position = value;
  49686. };
  49687. Object.defineProperty(ShadowLight.prototype, "position", {
  49688. /**
  49689. * Sets the position the shadow will be casted from. Also use as the light position for both
  49690. * point and spot lights.
  49691. */
  49692. get: function () {
  49693. return this._position;
  49694. },
  49695. /**
  49696. * Sets the position the shadow will be casted from. Also use as the light position for both
  49697. * point and spot lights.
  49698. */
  49699. set: function (value) {
  49700. this._setPosition(value);
  49701. },
  49702. enumerable: true,
  49703. configurable: true
  49704. });
  49705. ShadowLight.prototype._setDirection = function (value) {
  49706. this._direction = value;
  49707. };
  49708. Object.defineProperty(ShadowLight.prototype, "direction", {
  49709. /**
  49710. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49711. * Also use as the light direction on spot and directional lights.
  49712. */
  49713. get: function () {
  49714. return this._direction;
  49715. },
  49716. /**
  49717. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49718. * Also use as the light direction on spot and directional lights.
  49719. */
  49720. set: function (value) {
  49721. this._setDirection(value);
  49722. },
  49723. enumerable: true,
  49724. configurable: true
  49725. });
  49726. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49727. /**
  49728. * Gets the shadow projection clipping minimum z value.
  49729. */
  49730. get: function () {
  49731. return this._shadowMinZ;
  49732. },
  49733. /**
  49734. * Sets the shadow projection clipping minimum z value.
  49735. */
  49736. set: function (value) {
  49737. this._shadowMinZ = value;
  49738. this.forceProjectionMatrixCompute();
  49739. },
  49740. enumerable: true,
  49741. configurable: true
  49742. });
  49743. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49744. /**
  49745. * Sets the shadow projection clipping maximum z value.
  49746. */
  49747. get: function () {
  49748. return this._shadowMaxZ;
  49749. },
  49750. /**
  49751. * Gets the shadow projection clipping maximum z value.
  49752. */
  49753. set: function (value) {
  49754. this._shadowMaxZ = value;
  49755. this.forceProjectionMatrixCompute();
  49756. },
  49757. enumerable: true,
  49758. configurable: true
  49759. });
  49760. /**
  49761. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49762. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49763. */
  49764. ShadowLight.prototype.computeTransformedInformation = function () {
  49765. if (this.parent && this.parent.getWorldMatrix) {
  49766. if (!this.transformedPosition) {
  49767. this.transformedPosition = BABYLON.Vector3.Zero();
  49768. }
  49769. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49770. // In case the direction is present.
  49771. if (this.direction) {
  49772. if (!this.transformedDirection) {
  49773. this.transformedDirection = BABYLON.Vector3.Zero();
  49774. }
  49775. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49776. }
  49777. return true;
  49778. }
  49779. return false;
  49780. };
  49781. /**
  49782. * Return the depth scale used for the shadow map.
  49783. * @returns the depth scale.
  49784. */
  49785. ShadowLight.prototype.getDepthScale = function () {
  49786. return 50.0;
  49787. };
  49788. /**
  49789. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49790. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49791. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49792. */
  49793. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49794. return this.transformedDirection ? this.transformedDirection : this.direction;
  49795. };
  49796. /**
  49797. * Returns the ShadowLight absolute position in the World.
  49798. * @returns the position vector in world space
  49799. */
  49800. ShadowLight.prototype.getAbsolutePosition = function () {
  49801. return this.transformedPosition ? this.transformedPosition : this.position;
  49802. };
  49803. /**
  49804. * Sets the ShadowLight direction toward the passed target.
  49805. * @param target The point tot target in local space
  49806. * @returns the updated ShadowLight direction
  49807. */
  49808. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49809. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49810. return this.direction;
  49811. };
  49812. /**
  49813. * Returns the light rotation in euler definition.
  49814. * @returns the x y z rotation in local space.
  49815. */
  49816. ShadowLight.prototype.getRotation = function () {
  49817. this.direction.normalize();
  49818. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49819. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49820. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49821. };
  49822. /**
  49823. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49824. * @returns true if a cube texture needs to be use
  49825. */
  49826. ShadowLight.prototype.needCube = function () {
  49827. return false;
  49828. };
  49829. /**
  49830. * Detects if the projection matrix requires to be recomputed this frame.
  49831. * @returns true if it requires to be recomputed otherwise, false.
  49832. */
  49833. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49834. return this._needProjectionMatrixCompute;
  49835. };
  49836. /**
  49837. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49838. */
  49839. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49840. this._needProjectionMatrixCompute = true;
  49841. };
  49842. /**
  49843. * Get the world matrix of the sahdow lights.
  49844. * @hidden Internal Use Only
  49845. */
  49846. ShadowLight.prototype._getWorldMatrix = function () {
  49847. if (!this._worldMatrix) {
  49848. this._worldMatrix = BABYLON.Matrix.Identity();
  49849. }
  49850. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49851. return this._worldMatrix;
  49852. };
  49853. /**
  49854. * Gets the minZ used for shadow according to both the scene and the light.
  49855. * @param activeCamera The camera we are returning the min for
  49856. * @returns the depth min z
  49857. */
  49858. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49859. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49860. };
  49861. /**
  49862. * Gets the maxZ used for shadow according to both the scene and the light.
  49863. * @param activeCamera The camera we are returning the max for
  49864. * @returns the depth max z
  49865. */
  49866. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49867. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49868. };
  49869. /**
  49870. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49871. * @param matrix The materix to updated with the projection information
  49872. * @param viewMatrix The transform matrix of the light
  49873. * @param renderList The list of mesh to render in the map
  49874. * @returns The current light
  49875. */
  49876. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49877. if (this.customProjectionMatrixBuilder) {
  49878. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49879. }
  49880. else {
  49881. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49882. }
  49883. return this;
  49884. };
  49885. __decorate([
  49886. BABYLON.serializeAsVector3()
  49887. ], ShadowLight.prototype, "position", null);
  49888. __decorate([
  49889. BABYLON.serializeAsVector3()
  49890. ], ShadowLight.prototype, "direction", null);
  49891. __decorate([
  49892. BABYLON.serialize()
  49893. ], ShadowLight.prototype, "shadowMinZ", null);
  49894. __decorate([
  49895. BABYLON.serialize()
  49896. ], ShadowLight.prototype, "shadowMaxZ", null);
  49897. return ShadowLight;
  49898. }(BABYLON.Light));
  49899. BABYLON.ShadowLight = ShadowLight;
  49900. })(BABYLON || (BABYLON = {}));
  49901. //# sourceMappingURL=babylon.shadowLight.js.map
  49902. var BABYLON;
  49903. (function (BABYLON) {
  49904. /**
  49905. * A point light is a light defined by an unique point in world space.
  49906. * The light is emitted in every direction from this point.
  49907. * A good example of a point light is a standard light bulb.
  49908. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49909. */
  49910. var PointLight = /** @class */ (function (_super) {
  49911. __extends(PointLight, _super);
  49912. /**
  49913. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49914. * A PointLight emits the light in every direction.
  49915. * It can cast shadows.
  49916. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49917. * ```javascript
  49918. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49919. * ```
  49920. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49921. * @param name The light friendly name
  49922. * @param position The position of the point light in the scene
  49923. * @param scene The scene the lights belongs to
  49924. */
  49925. function PointLight(name, position, scene) {
  49926. var _this = _super.call(this, name, scene) || this;
  49927. _this._shadowAngle = Math.PI / 2;
  49928. _this.position = position;
  49929. return _this;
  49930. }
  49931. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49932. /**
  49933. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49934. * This specifies what angle the shadow will use to be created.
  49935. *
  49936. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49937. */
  49938. get: function () {
  49939. return this._shadowAngle;
  49940. },
  49941. /**
  49942. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49943. * This specifies what angle the shadow will use to be created.
  49944. *
  49945. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49946. */
  49947. set: function (value) {
  49948. this._shadowAngle = value;
  49949. this.forceProjectionMatrixCompute();
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. Object.defineProperty(PointLight.prototype, "direction", {
  49955. /**
  49956. * Gets the direction if it has been set.
  49957. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49958. */
  49959. get: function () {
  49960. return this._direction;
  49961. },
  49962. /**
  49963. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49964. */
  49965. set: function (value) {
  49966. var previousNeedCube = this.needCube();
  49967. this._direction = value;
  49968. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49969. this._shadowGenerator.recreateShadowMap();
  49970. }
  49971. },
  49972. enumerable: true,
  49973. configurable: true
  49974. });
  49975. /**
  49976. * Returns the string "PointLight"
  49977. * @returns the class name
  49978. */
  49979. PointLight.prototype.getClassName = function () {
  49980. return "PointLight";
  49981. };
  49982. /**
  49983. * Returns the integer 0.
  49984. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49985. */
  49986. PointLight.prototype.getTypeID = function () {
  49987. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49988. };
  49989. /**
  49990. * Specifies wether or not the shadowmap should be a cube texture.
  49991. * @returns true if the shadowmap needs to be a cube texture.
  49992. */
  49993. PointLight.prototype.needCube = function () {
  49994. return !this.direction;
  49995. };
  49996. /**
  49997. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49998. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49999. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50000. */
  50001. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50002. if (this.direction) {
  50003. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50004. }
  50005. else {
  50006. switch (faceIndex) {
  50007. case 0:
  50008. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50009. case 1:
  50010. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50011. case 2:
  50012. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50013. case 3:
  50014. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50015. case 4:
  50016. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50017. case 5:
  50018. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50019. }
  50020. }
  50021. return BABYLON.Vector3.Zero();
  50022. };
  50023. /**
  50024. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50025. * - fov = PI / 2
  50026. * - aspect ratio : 1.0
  50027. * - z-near and far equal to the active camera minZ and maxZ.
  50028. * Returns the PointLight.
  50029. */
  50030. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50031. var activeCamera = this.getScene().activeCamera;
  50032. if (!activeCamera) {
  50033. return;
  50034. }
  50035. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50036. };
  50037. PointLight.prototype._buildUniformLayout = function () {
  50038. this._uniformBuffer.addUniform("vLightData", 4);
  50039. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50040. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50041. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50042. this._uniformBuffer.addUniform("depthValues", 2);
  50043. this._uniformBuffer.create();
  50044. };
  50045. /**
  50046. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50047. * @param effect The effect to update
  50048. * @param lightIndex The index of the light in the effect to update
  50049. * @returns The point light
  50050. */
  50051. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50052. if (this.computeTransformedInformation()) {
  50053. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50054. return this;
  50055. }
  50056. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50057. return this;
  50058. };
  50059. __decorate([
  50060. BABYLON.serialize()
  50061. ], PointLight.prototype, "shadowAngle", null);
  50062. return PointLight;
  50063. }(BABYLON.ShadowLight));
  50064. BABYLON.PointLight = PointLight;
  50065. })(BABYLON || (BABYLON = {}));
  50066. //# sourceMappingURL=babylon.pointLight.js.map
  50067. var BABYLON;
  50068. (function (BABYLON) {
  50069. /**
  50070. * A directional light is defined by a direction (what a surprise!).
  50071. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50072. * 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.
  50073. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50074. */
  50075. var DirectionalLight = /** @class */ (function (_super) {
  50076. __extends(DirectionalLight, _super);
  50077. /**
  50078. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50079. * The directional light is emitted from everywhere in the given direction.
  50080. * It can cast shawdows.
  50081. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50082. * @param name The friendly name of the light
  50083. * @param direction The direction of the light
  50084. * @param scene The scene the light belongs to
  50085. */
  50086. function DirectionalLight(name, direction, scene) {
  50087. var _this = _super.call(this, name, scene) || this;
  50088. _this._shadowFrustumSize = 0;
  50089. _this._shadowOrthoScale = 0.1;
  50090. /**
  50091. * Automatically compute the projection matrix to best fit (including all the casters)
  50092. * on each frame.
  50093. */
  50094. _this.autoUpdateExtends = true;
  50095. // Cache
  50096. _this._orthoLeft = Number.MAX_VALUE;
  50097. _this._orthoRight = Number.MIN_VALUE;
  50098. _this._orthoTop = Number.MIN_VALUE;
  50099. _this._orthoBottom = Number.MAX_VALUE;
  50100. _this.position = direction.scale(-1.0);
  50101. _this.direction = direction;
  50102. return _this;
  50103. }
  50104. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50105. /**
  50106. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50107. */
  50108. get: function () {
  50109. return this._shadowFrustumSize;
  50110. },
  50111. /**
  50112. * Specifies a fix frustum size for the shadow generation.
  50113. */
  50114. set: function (value) {
  50115. this._shadowFrustumSize = value;
  50116. this.forceProjectionMatrixCompute();
  50117. },
  50118. enumerable: true,
  50119. configurable: true
  50120. });
  50121. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50122. /**
  50123. * Gets the shadow projection scale against the optimal computed one.
  50124. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50125. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50126. */
  50127. get: function () {
  50128. return this._shadowOrthoScale;
  50129. },
  50130. /**
  50131. * Sets the shadow projection scale against the optimal computed one.
  50132. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50133. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50134. */
  50135. set: function (value) {
  50136. this._shadowOrthoScale = value;
  50137. this.forceProjectionMatrixCompute();
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. /**
  50143. * Returns the string "DirectionalLight".
  50144. * @return The class name
  50145. */
  50146. DirectionalLight.prototype.getClassName = function () {
  50147. return "DirectionalLight";
  50148. };
  50149. /**
  50150. * Returns the integer 1.
  50151. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50152. */
  50153. DirectionalLight.prototype.getTypeID = function () {
  50154. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50155. };
  50156. /**
  50157. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50158. * Returns the DirectionalLight Shadow projection matrix.
  50159. */
  50160. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50161. if (this.shadowFrustumSize > 0) {
  50162. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50163. }
  50164. else {
  50165. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50166. }
  50167. };
  50168. /**
  50169. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50170. * Returns the DirectionalLight Shadow projection matrix.
  50171. */
  50172. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50173. var activeCamera = this.getScene().activeCamera;
  50174. if (!activeCamera) {
  50175. return;
  50176. }
  50177. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50178. };
  50179. /**
  50180. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50181. * Returns the DirectionalLight Shadow projection matrix.
  50182. */
  50183. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50184. var activeCamera = this.getScene().activeCamera;
  50185. if (!activeCamera) {
  50186. return;
  50187. }
  50188. // Check extends
  50189. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50190. var tempVector3 = BABYLON.Vector3.Zero();
  50191. this._orthoLeft = Number.MAX_VALUE;
  50192. this._orthoRight = Number.MIN_VALUE;
  50193. this._orthoTop = Number.MIN_VALUE;
  50194. this._orthoBottom = Number.MAX_VALUE;
  50195. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50196. var mesh = renderList[meshIndex];
  50197. if (!mesh) {
  50198. continue;
  50199. }
  50200. var boundingInfo = mesh.getBoundingInfo();
  50201. var boundingBox = boundingInfo.boundingBox;
  50202. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50203. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50204. if (tempVector3.x < this._orthoLeft)
  50205. this._orthoLeft = tempVector3.x;
  50206. if (tempVector3.y < this._orthoBottom)
  50207. this._orthoBottom = tempVector3.y;
  50208. if (tempVector3.x > this._orthoRight)
  50209. this._orthoRight = tempVector3.x;
  50210. if (tempVector3.y > this._orthoTop)
  50211. this._orthoTop = tempVector3.y;
  50212. }
  50213. }
  50214. }
  50215. var xOffset = this._orthoRight - this._orthoLeft;
  50216. var yOffset = this._orthoTop - this._orthoBottom;
  50217. 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);
  50218. };
  50219. DirectionalLight.prototype._buildUniformLayout = function () {
  50220. this._uniformBuffer.addUniform("vLightData", 4);
  50221. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50222. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50223. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50224. this._uniformBuffer.addUniform("depthValues", 2);
  50225. this._uniformBuffer.create();
  50226. };
  50227. /**
  50228. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50229. * @param effect The effect to update
  50230. * @param lightIndex The index of the light in the effect to update
  50231. * @returns The directional light
  50232. */
  50233. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50234. if (this.computeTransformedInformation()) {
  50235. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50236. return this;
  50237. }
  50238. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50239. return this;
  50240. };
  50241. /**
  50242. * Gets the minZ used for shadow according to both the scene and the light.
  50243. *
  50244. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50245. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50246. * @param activeCamera The camera we are returning the min for
  50247. * @returns the depth min z
  50248. */
  50249. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50250. return 1;
  50251. };
  50252. /**
  50253. * Gets the maxZ used for shadow according to both the scene and the light.
  50254. *
  50255. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50256. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50257. * @param activeCamera The camera we are returning the max for
  50258. * @returns the depth max z
  50259. */
  50260. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50261. return 1;
  50262. };
  50263. __decorate([
  50264. BABYLON.serialize()
  50265. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50266. __decorate([
  50267. BABYLON.serialize()
  50268. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50269. __decorate([
  50270. BABYLON.serialize()
  50271. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50272. return DirectionalLight;
  50273. }(BABYLON.ShadowLight));
  50274. BABYLON.DirectionalLight = DirectionalLight;
  50275. })(BABYLON || (BABYLON = {}));
  50276. //# sourceMappingURL=babylon.directionalLight.js.map
  50277. var BABYLON;
  50278. (function (BABYLON) {
  50279. /**
  50280. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50281. * These values define a cone of light starting from the position, emitting toward the direction.
  50282. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50283. * and the exponent defines the speed of the decay of the light with distance (reach).
  50284. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50285. */
  50286. var SpotLight = /** @class */ (function (_super) {
  50287. __extends(SpotLight, _super);
  50288. /**
  50289. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50290. * It can cast shadows.
  50291. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50292. * @param name The light friendly name
  50293. * @param position The position of the spot light in the scene
  50294. * @param direction The direction of the light in the scene
  50295. * @param angle The cone angle of the light in Radians
  50296. * @param exponent The light decay speed with the distance from the emission spot
  50297. * @param scene The scene the lights belongs to
  50298. */
  50299. function SpotLight(name, position, direction, angle, exponent, scene) {
  50300. var _this = _super.call(this, name, scene) || this;
  50301. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50302. _this._projectionTextureLightNear = 1e-6;
  50303. _this._projectionTextureLightFar = 1000.0;
  50304. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50305. _this._projectionTextureViewLightDirty = true;
  50306. _this._projectionTextureProjectionLightDirty = true;
  50307. _this._projectionTextureDirty = true;
  50308. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50309. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50310. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50311. _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);
  50312. _this.position = position;
  50313. _this.direction = direction;
  50314. _this.angle = angle;
  50315. _this.exponent = exponent;
  50316. return _this;
  50317. }
  50318. Object.defineProperty(SpotLight.prototype, "angle", {
  50319. /**
  50320. * Gets the cone angle of the spot light in Radians.
  50321. */
  50322. get: function () {
  50323. return this._angle;
  50324. },
  50325. /**
  50326. * Sets the cone angle of the spot light in Radians.
  50327. */
  50328. set: function (value) {
  50329. this._angle = value;
  50330. this._projectionTextureProjectionLightDirty = true;
  50331. this.forceProjectionMatrixCompute();
  50332. },
  50333. enumerable: true,
  50334. configurable: true
  50335. });
  50336. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50337. /**
  50338. * Allows scaling the angle of the light for shadow generation only.
  50339. */
  50340. get: function () {
  50341. return this._shadowAngleScale;
  50342. },
  50343. /**
  50344. * Allows scaling the angle of the light for shadow generation only.
  50345. */
  50346. set: function (value) {
  50347. this._shadowAngleScale = value;
  50348. this.forceProjectionMatrixCompute();
  50349. },
  50350. enumerable: true,
  50351. configurable: true
  50352. });
  50353. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50354. /**
  50355. * Allows reading the projecton texture
  50356. */
  50357. get: function () {
  50358. return this._projectionTextureMatrix;
  50359. },
  50360. enumerable: true,
  50361. configurable: true
  50362. });
  50363. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50364. /**
  50365. * Gets the near clip of the Spotlight for texture projection.
  50366. */
  50367. get: function () {
  50368. return this._projectionTextureLightNear;
  50369. },
  50370. /**
  50371. * Sets the near clip of the Spotlight for texture projection.
  50372. */
  50373. set: function (value) {
  50374. this._projectionTextureLightNear = value;
  50375. this._projectionTextureProjectionLightDirty = true;
  50376. },
  50377. enumerable: true,
  50378. configurable: true
  50379. });
  50380. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50381. /**
  50382. * Gets the far clip of the Spotlight for texture projection.
  50383. */
  50384. get: function () {
  50385. return this._projectionTextureLightFar;
  50386. },
  50387. /**
  50388. * Sets the far clip of the Spotlight for texture projection.
  50389. */
  50390. set: function (value) {
  50391. this._projectionTextureLightFar = value;
  50392. this._projectionTextureProjectionLightDirty = true;
  50393. },
  50394. enumerable: true,
  50395. configurable: true
  50396. });
  50397. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50398. /**
  50399. * Gets the Up vector of the Spotlight for texture projection.
  50400. */
  50401. get: function () {
  50402. return this._projectionTextureUpDirection;
  50403. },
  50404. /**
  50405. * Sets the Up vector of the Spotlight for texture projection.
  50406. */
  50407. set: function (value) {
  50408. this._projectionTextureUpDirection = value;
  50409. this._projectionTextureProjectionLightDirty = true;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50415. /**
  50416. * Gets the projection texture of the light.
  50417. */
  50418. get: function () {
  50419. return this._projectionTexture;
  50420. },
  50421. /**
  50422. * Sets the projection texture of the light.
  50423. */
  50424. set: function (value) {
  50425. this._projectionTexture = value;
  50426. this._projectionTextureDirty = true;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. /**
  50432. * Returns the string "SpotLight".
  50433. * @returns the class name
  50434. */
  50435. SpotLight.prototype.getClassName = function () {
  50436. return "SpotLight";
  50437. };
  50438. /**
  50439. * Returns the integer 2.
  50440. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50441. */
  50442. SpotLight.prototype.getTypeID = function () {
  50443. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50444. };
  50445. /**
  50446. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50447. */
  50448. SpotLight.prototype._setDirection = function (value) {
  50449. _super.prototype._setDirection.call(this, value);
  50450. this._projectionTextureViewLightDirty = true;
  50451. };
  50452. /**
  50453. * Overrides the position setter to recompute the projection texture view light Matrix.
  50454. */
  50455. SpotLight.prototype._setPosition = function (value) {
  50456. _super.prototype._setPosition.call(this, value);
  50457. this._projectionTextureViewLightDirty = true;
  50458. };
  50459. /**
  50460. * 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.
  50461. * Returns the SpotLight.
  50462. */
  50463. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50464. var activeCamera = this.getScene().activeCamera;
  50465. if (!activeCamera) {
  50466. return;
  50467. }
  50468. this._shadowAngleScale = this._shadowAngleScale || 1;
  50469. var angle = this._shadowAngleScale * this._angle;
  50470. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50471. };
  50472. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50473. this._projectionTextureViewLightDirty = false;
  50474. this._projectionTextureDirty = true;
  50475. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50476. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50477. };
  50478. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50479. this._projectionTextureProjectionLightDirty = false;
  50480. this._projectionTextureDirty = true;
  50481. var light_far = this.projectionTextureLightFar;
  50482. var light_near = this.projectionTextureLightNear;
  50483. var P = light_far / (light_far - light_near);
  50484. var Q = -P * light_near;
  50485. var S = 1.0 / Math.tan(this._angle / 2.0);
  50486. var A = 1.0;
  50487. 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);
  50488. };
  50489. /**
  50490. * Main function for light texture projection matrix computing.
  50491. */
  50492. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50493. this._projectionTextureDirty = false;
  50494. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50495. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50496. };
  50497. SpotLight.prototype._buildUniformLayout = function () {
  50498. this._uniformBuffer.addUniform("vLightData", 4);
  50499. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50500. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50501. this._uniformBuffer.addUniform("vLightDirection", 3);
  50502. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50503. this._uniformBuffer.addUniform("depthValues", 2);
  50504. this._uniformBuffer.create();
  50505. };
  50506. /**
  50507. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50508. * @param effect The effect to update
  50509. * @param lightIndex The index of the light in the effect to update
  50510. * @returns The spot light
  50511. */
  50512. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50513. var normalizeDirection;
  50514. if (this.computeTransformedInformation()) {
  50515. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50516. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50517. }
  50518. else {
  50519. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50520. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50521. }
  50522. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50523. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50524. if (this._projectionTextureViewLightDirty) {
  50525. this._computeProjectionTextureViewLightMatrix();
  50526. }
  50527. if (this._projectionTextureProjectionLightDirty) {
  50528. this._computeProjectionTextureProjectionLightMatrix();
  50529. }
  50530. if (this._projectionTextureDirty) {
  50531. this._computeProjectionTextureMatrix();
  50532. }
  50533. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50534. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50535. }
  50536. return this;
  50537. };
  50538. /**
  50539. * Disposes the light and the associated resources.
  50540. */
  50541. SpotLight.prototype.dispose = function () {
  50542. _super.prototype.dispose.call(this);
  50543. if (this._projectionTexture) {
  50544. this._projectionTexture.dispose();
  50545. }
  50546. };
  50547. __decorate([
  50548. BABYLON.serialize()
  50549. ], SpotLight.prototype, "angle", null);
  50550. __decorate([
  50551. BABYLON.serialize()
  50552. ], SpotLight.prototype, "shadowAngleScale", null);
  50553. __decorate([
  50554. BABYLON.serialize()
  50555. ], SpotLight.prototype, "exponent", void 0);
  50556. __decorate([
  50557. BABYLON.serialize()
  50558. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50559. __decorate([
  50560. BABYLON.serialize()
  50561. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50562. __decorate([
  50563. BABYLON.serialize()
  50564. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50565. __decorate([
  50566. BABYLON.serializeAsTexture("projectedLightTexture")
  50567. ], SpotLight.prototype, "_projectionTexture", void 0);
  50568. return SpotLight;
  50569. }(BABYLON.ShadowLight));
  50570. BABYLON.SpotLight = SpotLight;
  50571. })(BABYLON || (BABYLON = {}));
  50572. //# sourceMappingURL=babylon.spotLight.js.map
  50573. var BABYLON;
  50574. (function (BABYLON) {
  50575. /**
  50576. * Class used to override all child animations of a given target
  50577. */
  50578. var AnimationPropertiesOverride = /** @class */ (function () {
  50579. function AnimationPropertiesOverride() {
  50580. /**
  50581. * Gets or sets a value indicating if animation blending must be used
  50582. */
  50583. this.enableBlending = false;
  50584. /**
  50585. * Gets or sets the blending speed to use when enableBlending is true
  50586. */
  50587. this.blendingSpeed = 0.01;
  50588. /**
  50589. * Gets or sets the default loop mode to use
  50590. */
  50591. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50592. }
  50593. return AnimationPropertiesOverride;
  50594. }());
  50595. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50596. })(BABYLON || (BABYLON = {}));
  50597. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50598. var BABYLON;
  50599. (function (BABYLON) {
  50600. /**
  50601. * Represents the range of an animation
  50602. */
  50603. var AnimationRange = /** @class */ (function () {
  50604. /**
  50605. * Initializes the range of an animation
  50606. * @param name The name of the animation range
  50607. * @param from The starting frame of the animation
  50608. * @param to The ending frame of the animation
  50609. */
  50610. function AnimationRange(
  50611. /**The name of the animation range**/
  50612. name,
  50613. /**The starting frame of the animation */
  50614. from,
  50615. /**The ending frame of the animation*/
  50616. to) {
  50617. this.name = name;
  50618. this.from = from;
  50619. this.to = to;
  50620. }
  50621. /**
  50622. * Makes a copy of the animation range
  50623. * @returns A copy of the animation range
  50624. */
  50625. AnimationRange.prototype.clone = function () {
  50626. return new AnimationRange(this.name, this.from, this.to);
  50627. };
  50628. return AnimationRange;
  50629. }());
  50630. BABYLON.AnimationRange = AnimationRange;
  50631. /**
  50632. * Composed of a frame, and an action function
  50633. */
  50634. var AnimationEvent = /** @class */ (function () {
  50635. /**
  50636. * Initializes the animation event
  50637. * @param frame The frame for which the event is triggered
  50638. * @param action The event to perform when triggered
  50639. * @param onlyOnce Specifies if the event should be triggered only once
  50640. */
  50641. function AnimationEvent(
  50642. /** The frame for which the event is triggered **/
  50643. frame,
  50644. /** The event to perform when triggered **/
  50645. action,
  50646. /** Specifies if the event should be triggered only once**/
  50647. onlyOnce) {
  50648. this.frame = frame;
  50649. this.action = action;
  50650. this.onlyOnce = onlyOnce;
  50651. /**
  50652. * Specifies if the animation event is done
  50653. */
  50654. this.isDone = false;
  50655. }
  50656. /** @hidden */
  50657. AnimationEvent.prototype._clone = function () {
  50658. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50659. };
  50660. return AnimationEvent;
  50661. }());
  50662. BABYLON.AnimationEvent = AnimationEvent;
  50663. /**
  50664. * A cursor which tracks a point on a path
  50665. */
  50666. var PathCursor = /** @class */ (function () {
  50667. /**
  50668. * Initializes the path cursor
  50669. * @param path The path to track
  50670. */
  50671. function PathCursor(path) {
  50672. this.path = path;
  50673. /**
  50674. * Stores path cursor callbacks for when an onchange event is triggered
  50675. */
  50676. this._onchange = new Array();
  50677. /**
  50678. * The value of the path cursor
  50679. */
  50680. this.value = 0;
  50681. /**
  50682. * The animation array of the path cursor
  50683. */
  50684. this.animations = new Array();
  50685. }
  50686. /**
  50687. * Gets the cursor point on the path
  50688. * @returns A point on the path cursor at the cursor location
  50689. */
  50690. PathCursor.prototype.getPoint = function () {
  50691. var point = this.path.getPointAtLengthPosition(this.value);
  50692. return new BABYLON.Vector3(point.x, 0, point.y);
  50693. };
  50694. /**
  50695. * Moves the cursor ahead by the step amount
  50696. * @param step The amount to move the cursor forward
  50697. * @returns This path cursor
  50698. */
  50699. PathCursor.prototype.moveAhead = function (step) {
  50700. if (step === void 0) { step = 0.002; }
  50701. this.move(step);
  50702. return this;
  50703. };
  50704. /**
  50705. * Moves the cursor behind by the step amount
  50706. * @param step The amount to move the cursor back
  50707. * @returns This path cursor
  50708. */
  50709. PathCursor.prototype.moveBack = function (step) {
  50710. if (step === void 0) { step = 0.002; }
  50711. this.move(-step);
  50712. return this;
  50713. };
  50714. /**
  50715. * Moves the cursor by the step amount
  50716. * If the step amount is greater than one, an exception is thrown
  50717. * @param step The amount to move the cursor
  50718. * @returns This path cursor
  50719. */
  50720. PathCursor.prototype.move = function (step) {
  50721. if (Math.abs(step) > 1) {
  50722. throw "step size should be less than 1.";
  50723. }
  50724. this.value += step;
  50725. this.ensureLimits();
  50726. this.raiseOnChange();
  50727. return this;
  50728. };
  50729. /**
  50730. * Ensures that the value is limited between zero and one
  50731. * @returns This path cursor
  50732. */
  50733. PathCursor.prototype.ensureLimits = function () {
  50734. while (this.value > 1) {
  50735. this.value -= 1;
  50736. }
  50737. while (this.value < 0) {
  50738. this.value += 1;
  50739. }
  50740. return this;
  50741. };
  50742. /**
  50743. * Runs onchange callbacks on change (used by the animation engine)
  50744. * @returns This path cursor
  50745. */
  50746. PathCursor.prototype.raiseOnChange = function () {
  50747. var _this = this;
  50748. this._onchange.forEach(function (f) { return f(_this); });
  50749. return this;
  50750. };
  50751. /**
  50752. * Executes a function on change
  50753. * @param f A path cursor onchange callback
  50754. * @returns This path cursor
  50755. */
  50756. PathCursor.prototype.onchange = function (f) {
  50757. this._onchange.push(f);
  50758. return this;
  50759. };
  50760. return PathCursor;
  50761. }());
  50762. BABYLON.PathCursor = PathCursor;
  50763. /**
  50764. * Enum for the animation key frame interpolation type
  50765. */
  50766. var AnimationKeyInterpolation;
  50767. (function (AnimationKeyInterpolation) {
  50768. /**
  50769. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50770. */
  50771. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50772. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50773. /**
  50774. * Class used to store any kind of animation
  50775. */
  50776. var Animation = /** @class */ (function () {
  50777. /**
  50778. * Initializes the animation
  50779. * @param name Name of the animation
  50780. * @param targetProperty Property to animate
  50781. * @param framePerSecond The frames per second of the animation
  50782. * @param dataType The data type of the animation
  50783. * @param loopMode The loop mode of the animation
  50784. * @param enableBlendings Specifies if blending should be enabled
  50785. */
  50786. function Animation(
  50787. /**Name of the animation */
  50788. name,
  50789. /**Property to animate */
  50790. targetProperty,
  50791. /**The frames per second of the animation */
  50792. framePerSecond,
  50793. /**The data type of the animation */
  50794. dataType,
  50795. /**The loop mode of the animation */
  50796. loopMode,
  50797. /**Specifies if blending should be enabled */
  50798. enableBlending) {
  50799. this.name = name;
  50800. this.targetProperty = targetProperty;
  50801. this.framePerSecond = framePerSecond;
  50802. this.dataType = dataType;
  50803. this.loopMode = loopMode;
  50804. this.enableBlending = enableBlending;
  50805. /**
  50806. * @hidden Internal use only
  50807. */
  50808. this._runtimeAnimations = new Array();
  50809. /**
  50810. * The set of event that will be linked to this animation
  50811. */
  50812. this._events = new Array();
  50813. /**
  50814. * Stores the blending speed of the animation
  50815. */
  50816. this.blendingSpeed = 0.01;
  50817. /**
  50818. * Stores the animation ranges for the animation
  50819. */
  50820. this._ranges = {};
  50821. this.targetPropertyPath = targetProperty.split(".");
  50822. this.dataType = dataType;
  50823. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50824. }
  50825. /**
  50826. * @hidden Internal use
  50827. */
  50828. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50829. var dataType = undefined;
  50830. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50831. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50832. }
  50833. else if (from instanceof BABYLON.Quaternion) {
  50834. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50835. }
  50836. else if (from instanceof BABYLON.Vector3) {
  50837. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50838. }
  50839. else if (from instanceof BABYLON.Vector2) {
  50840. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50841. }
  50842. else if (from instanceof BABYLON.Color3) {
  50843. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50844. }
  50845. else if (from instanceof BABYLON.Size) {
  50846. dataType = Animation.ANIMATIONTYPE_SIZE;
  50847. }
  50848. if (dataType == undefined) {
  50849. return null;
  50850. }
  50851. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50852. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50853. animation.setKeys(keys);
  50854. if (easingFunction !== undefined) {
  50855. animation.setEasingFunction(easingFunction);
  50856. }
  50857. return animation;
  50858. };
  50859. /**
  50860. * Sets up an animation
  50861. * @param property The property to animate
  50862. * @param animationType The animation type to apply
  50863. * @param framePerSecond The frames per second of the animation
  50864. * @param easingFunction The easing function used in the animation
  50865. * @returns The created animation
  50866. */
  50867. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50868. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50869. animation.setEasingFunction(easingFunction);
  50870. return animation;
  50871. };
  50872. /**
  50873. * Create and start an animation on a node
  50874. * @param name defines the name of the global animation that will be run on all nodes
  50875. * @param node defines the root node where the animation will take place
  50876. * @param targetProperty defines property to animate
  50877. * @param framePerSecond defines the number of frame per second yo use
  50878. * @param totalFrame defines the number of frames in total
  50879. * @param from defines the initial value
  50880. * @param to defines the final value
  50881. * @param loopMode defines which loop mode you want to use (off by default)
  50882. * @param easingFunction defines the easing function to use (linear by default)
  50883. * @param onAnimationEnd defines the callback to call when animation end
  50884. * @returns the animatable created for this animation
  50885. */
  50886. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50887. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50888. if (!animation) {
  50889. return null;
  50890. }
  50891. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50892. };
  50893. /**
  50894. * Create and start an animation on a node and its descendants
  50895. * @param name defines the name of the global animation that will be run on all nodes
  50896. * @param node defines the root node where the animation will take place
  50897. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50898. * @param targetProperty defines property to animate
  50899. * @param framePerSecond defines the number of frame per second to use
  50900. * @param totalFrame defines the number of frames in total
  50901. * @param from defines the initial value
  50902. * @param to defines the final value
  50903. * @param loopMode defines which loop mode you want to use (off by default)
  50904. * @param easingFunction defines the easing function to use (linear by default)
  50905. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50906. * @returns the list of animatables created for all nodes
  50907. * @example https://www.babylonjs-playground.com/#MH0VLI
  50908. */
  50909. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50910. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50911. if (!animation) {
  50912. return null;
  50913. }
  50914. var scene = node.getScene();
  50915. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50916. };
  50917. /**
  50918. * Creates a new animation, merges it with the existing animations and starts it
  50919. * @param name Name of the animation
  50920. * @param node Node which contains the scene that begins the animations
  50921. * @param targetProperty Specifies which property to animate
  50922. * @param framePerSecond The frames per second of the animation
  50923. * @param totalFrame The total number of frames
  50924. * @param from The frame at the beginning of the animation
  50925. * @param to The frame at the end of the animation
  50926. * @param loopMode Specifies the loop mode of the animation
  50927. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50928. * @param onAnimationEnd Callback to run once the animation is complete
  50929. * @returns Nullable animation
  50930. */
  50931. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50932. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50933. if (!animation) {
  50934. return null;
  50935. }
  50936. node.animations.push(animation);
  50937. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50938. };
  50939. /**
  50940. * Transition property of an host to the target Value
  50941. * @param property The property to transition
  50942. * @param targetValue The target Value of the property
  50943. * @param host The object where the property to animate belongs
  50944. * @param scene Scene used to run the animation
  50945. * @param frameRate Framerate (in frame/s) to use
  50946. * @param transition The transition type we want to use
  50947. * @param duration The duration of the animation, in milliseconds
  50948. * @param onAnimationEnd Callback trigger at the end of the animation
  50949. * @returns Nullable animation
  50950. */
  50951. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50952. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50953. if (duration <= 0) {
  50954. host[property] = targetValue;
  50955. if (onAnimationEnd) {
  50956. onAnimationEnd();
  50957. }
  50958. return null;
  50959. }
  50960. var endFrame = frameRate * (duration / 1000);
  50961. transition.setKeys([{
  50962. frame: 0,
  50963. value: host[property].clone ? host[property].clone() : host[property]
  50964. },
  50965. {
  50966. frame: endFrame,
  50967. value: targetValue
  50968. }]);
  50969. if (!host.animations) {
  50970. host.animations = [];
  50971. }
  50972. host.animations.push(transition);
  50973. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50974. animation.onAnimationEnd = onAnimationEnd;
  50975. return animation;
  50976. };
  50977. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50978. /**
  50979. * Return the array of runtime animations currently using this animation
  50980. */
  50981. get: function () {
  50982. return this._runtimeAnimations;
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50988. /**
  50989. * Specifies if any of the runtime animations are currently running
  50990. */
  50991. get: function () {
  50992. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50993. var runtimeAnimation = _a[_i];
  50994. if (!runtimeAnimation.isStopped) {
  50995. return true;
  50996. }
  50997. }
  50998. return false;
  50999. },
  51000. enumerable: true,
  51001. configurable: true
  51002. });
  51003. // Methods
  51004. /**
  51005. * Converts the animation to a string
  51006. * @param fullDetails support for multiple levels of logging within scene loading
  51007. * @returns String form of the animation
  51008. */
  51009. Animation.prototype.toString = function (fullDetails) {
  51010. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51011. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51012. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51013. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51014. if (fullDetails) {
  51015. ret += ", Ranges: {";
  51016. var first = true;
  51017. for (var name in this._ranges) {
  51018. if (first) {
  51019. ret += ", ";
  51020. first = false;
  51021. }
  51022. ret += name;
  51023. }
  51024. ret += "}";
  51025. }
  51026. return ret;
  51027. };
  51028. /**
  51029. * Add an event to this animation
  51030. * @param event Event to add
  51031. */
  51032. Animation.prototype.addEvent = function (event) {
  51033. this._events.push(event);
  51034. };
  51035. /**
  51036. * Remove all events found at the given frame
  51037. * @param frame The frame to remove events from
  51038. */
  51039. Animation.prototype.removeEvents = function (frame) {
  51040. for (var index = 0; index < this._events.length; index++) {
  51041. if (this._events[index].frame === frame) {
  51042. this._events.splice(index, 1);
  51043. index--;
  51044. }
  51045. }
  51046. };
  51047. /**
  51048. * Retrieves all the events from the animation
  51049. * @returns Events from the animation
  51050. */
  51051. Animation.prototype.getEvents = function () {
  51052. return this._events;
  51053. };
  51054. /**
  51055. * Creates an animation range
  51056. * @param name Name of the animation range
  51057. * @param from Starting frame of the animation range
  51058. * @param to Ending frame of the animation
  51059. */
  51060. Animation.prototype.createRange = function (name, from, to) {
  51061. // check name not already in use; could happen for bones after serialized
  51062. if (!this._ranges[name]) {
  51063. this._ranges[name] = new AnimationRange(name, from, to);
  51064. }
  51065. };
  51066. /**
  51067. * Deletes an animation range by name
  51068. * @param name Name of the animation range to delete
  51069. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51070. */
  51071. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51072. if (deleteFrames === void 0) { deleteFrames = true; }
  51073. var range = this._ranges[name];
  51074. if (!range) {
  51075. return;
  51076. }
  51077. if (deleteFrames) {
  51078. var from = range.from;
  51079. var to = range.to;
  51080. // this loop MUST go high to low for multiple splices to work
  51081. for (var key = this._keys.length - 1; key >= 0; key--) {
  51082. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51083. this._keys.splice(key, 1);
  51084. }
  51085. }
  51086. }
  51087. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51088. };
  51089. /**
  51090. * Gets the animation range by name, or null if not defined
  51091. * @param name Name of the animation range
  51092. * @returns Nullable animation range
  51093. */
  51094. Animation.prototype.getRange = function (name) {
  51095. return this._ranges[name];
  51096. };
  51097. /**
  51098. * Gets the key frames from the animation
  51099. * @returns The key frames of the animation
  51100. */
  51101. Animation.prototype.getKeys = function () {
  51102. return this._keys;
  51103. };
  51104. /**
  51105. * Gets the highest frame rate of the animation
  51106. * @returns Highest frame rate of the animation
  51107. */
  51108. Animation.prototype.getHighestFrame = function () {
  51109. var ret = 0;
  51110. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51111. if (ret < this._keys[key].frame) {
  51112. ret = this._keys[key].frame;
  51113. }
  51114. }
  51115. return ret;
  51116. };
  51117. /**
  51118. * Gets the easing function of the animation
  51119. * @returns Easing function of the animation
  51120. */
  51121. Animation.prototype.getEasingFunction = function () {
  51122. return this._easingFunction;
  51123. };
  51124. /**
  51125. * Sets the easing function of the animation
  51126. * @param easingFunction A custom mathematical formula for animation
  51127. */
  51128. Animation.prototype.setEasingFunction = function (easingFunction) {
  51129. this._easingFunction = easingFunction;
  51130. };
  51131. /**
  51132. * Interpolates a scalar linearly
  51133. * @param startValue Start value of the animation curve
  51134. * @param endValue End value of the animation curve
  51135. * @param gradient Scalar amount to interpolate
  51136. * @returns Interpolated scalar value
  51137. */
  51138. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51139. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51140. };
  51141. /**
  51142. * Interpolates a scalar cubically
  51143. * @param startValue Start value of the animation curve
  51144. * @param outTangent End tangent of the animation
  51145. * @param endValue End value of the animation curve
  51146. * @param inTangent Start tangent of the animation curve
  51147. * @param gradient Scalar amount to interpolate
  51148. * @returns Interpolated scalar value
  51149. */
  51150. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51151. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51152. };
  51153. /**
  51154. * Interpolates a quaternion using a spherical linear interpolation
  51155. * @param startValue Start value of the animation curve
  51156. * @param endValue End value of the animation curve
  51157. * @param gradient Scalar amount to interpolate
  51158. * @returns Interpolated quaternion value
  51159. */
  51160. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51161. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51162. };
  51163. /**
  51164. * Interpolates a quaternion cubically
  51165. * @param startValue Start value of the animation curve
  51166. * @param outTangent End tangent of the animation curve
  51167. * @param endValue End value of the animation curve
  51168. * @param inTangent Start tangent of the animation curve
  51169. * @param gradient Scalar amount to interpolate
  51170. * @returns Interpolated quaternion value
  51171. */
  51172. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51173. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51174. };
  51175. /**
  51176. * Interpolates a Vector3 linearl
  51177. * @param startValue Start value of the animation curve
  51178. * @param endValue End value of the animation curve
  51179. * @param gradient Scalar amount to interpolate
  51180. * @returns Interpolated scalar value
  51181. */
  51182. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51183. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51184. };
  51185. /**
  51186. * Interpolates a Vector3 cubically
  51187. * @param startValue Start value of the animation curve
  51188. * @param outTangent End tangent of the animation
  51189. * @param endValue End value of the animation curve
  51190. * @param inTangent Start tangent of the animation curve
  51191. * @param gradient Scalar amount to interpolate
  51192. * @returns InterpolatedVector3 value
  51193. */
  51194. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51195. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51196. };
  51197. /**
  51198. * Interpolates a Vector2 linearly
  51199. * @param startValue Start value of the animation curve
  51200. * @param endValue End value of the animation curve
  51201. * @param gradient Scalar amount to interpolate
  51202. * @returns Interpolated Vector2 value
  51203. */
  51204. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51205. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51206. };
  51207. /**
  51208. * Interpolates a Vector2 cubically
  51209. * @param startValue Start value of the animation curve
  51210. * @param outTangent End tangent of the animation
  51211. * @param endValue End value of the animation curve
  51212. * @param inTangent Start tangent of the animation curve
  51213. * @param gradient Scalar amount to interpolate
  51214. * @returns Interpolated Vector2 value
  51215. */
  51216. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51217. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51218. };
  51219. /**
  51220. * Interpolates a size linearly
  51221. * @param startValue Start value of the animation curve
  51222. * @param endValue End value of the animation curve
  51223. * @param gradient Scalar amount to interpolate
  51224. * @returns Interpolated Size value
  51225. */
  51226. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51227. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51228. };
  51229. /**
  51230. * Interpolates a Color3 linearly
  51231. * @param startValue Start value of the animation curve
  51232. * @param endValue End value of the animation curve
  51233. * @param gradient Scalar amount to interpolate
  51234. * @returns Interpolated Color3 value
  51235. */
  51236. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51237. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51238. };
  51239. /**
  51240. * @hidden Internal use only
  51241. */
  51242. Animation.prototype._getKeyValue = function (value) {
  51243. if (typeof value === "function") {
  51244. return value();
  51245. }
  51246. return value;
  51247. };
  51248. /**
  51249. * @hidden Internal use only
  51250. */
  51251. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51252. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51253. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51254. }
  51255. var keys = this.getKeys();
  51256. // Try to get a hash to find the right key
  51257. 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));
  51258. if (keys[startKeyIndex].frame >= currentFrame) {
  51259. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51260. startKeyIndex--;
  51261. }
  51262. }
  51263. for (var key = startKeyIndex; key < keys.length; key++) {
  51264. var endKey = keys[key + 1];
  51265. if (endKey.frame >= currentFrame) {
  51266. var startKey = keys[key];
  51267. var startValue = this._getKeyValue(startKey.value);
  51268. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51269. return startValue;
  51270. }
  51271. var endValue = this._getKeyValue(endKey.value);
  51272. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51273. var frameDelta = endKey.frame - startKey.frame;
  51274. // gradient : percent of currentFrame between the frame inf and the frame sup
  51275. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51276. // check for easingFunction and correction of gradient
  51277. var easingFunction = this.getEasingFunction();
  51278. if (easingFunction != null) {
  51279. gradient = easingFunction.ease(gradient);
  51280. }
  51281. switch (this.dataType) {
  51282. // Float
  51283. case Animation.ANIMATIONTYPE_FLOAT:
  51284. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51285. switch (loopMode) {
  51286. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51287. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51288. return floatValue;
  51289. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51290. return offsetValue * repeatCount + floatValue;
  51291. }
  51292. break;
  51293. // Quaternion
  51294. case Animation.ANIMATIONTYPE_QUATERNION:
  51295. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51296. switch (loopMode) {
  51297. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51298. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51299. return quatValue;
  51300. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51301. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51302. }
  51303. return quatValue;
  51304. // Vector3
  51305. case Animation.ANIMATIONTYPE_VECTOR3:
  51306. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51307. switch (loopMode) {
  51308. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51309. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51310. return vec3Value;
  51311. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51312. return vec3Value.add(offsetValue.scale(repeatCount));
  51313. }
  51314. // Vector2
  51315. case Animation.ANIMATIONTYPE_VECTOR2:
  51316. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51317. switch (loopMode) {
  51318. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51319. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51320. return vec2Value;
  51321. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51322. return vec2Value.add(offsetValue.scale(repeatCount));
  51323. }
  51324. // Size
  51325. case Animation.ANIMATIONTYPE_SIZE:
  51326. switch (loopMode) {
  51327. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51328. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51329. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51330. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51331. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51332. }
  51333. // Color3
  51334. case Animation.ANIMATIONTYPE_COLOR3:
  51335. switch (loopMode) {
  51336. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51337. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51338. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51339. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51340. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51341. }
  51342. // Matrix
  51343. case Animation.ANIMATIONTYPE_MATRIX:
  51344. switch (loopMode) {
  51345. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51346. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51347. if (Animation.AllowMatricesInterpolation) {
  51348. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51349. }
  51350. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51351. return startValue;
  51352. }
  51353. default:
  51354. break;
  51355. }
  51356. break;
  51357. }
  51358. }
  51359. return this._getKeyValue(keys[keys.length - 1].value);
  51360. };
  51361. /**
  51362. * Defines the function to use to interpolate matrices
  51363. * @param startValue defines the start matrix
  51364. * @param endValue defines the end matrix
  51365. * @param gradient defines the gradient between both matrices
  51366. * @param result defines an optional target matrix where to store the interpolation
  51367. * @returns the interpolated matrix
  51368. */
  51369. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51370. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51371. if (result) {
  51372. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51373. return result;
  51374. }
  51375. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51376. }
  51377. if (result) {
  51378. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51379. return result;
  51380. }
  51381. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51382. };
  51383. /**
  51384. * Makes a copy of the animation
  51385. * @returns Cloned animation
  51386. */
  51387. Animation.prototype.clone = function () {
  51388. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51389. clone.enableBlending = this.enableBlending;
  51390. clone.blendingSpeed = this.blendingSpeed;
  51391. if (this._keys) {
  51392. clone.setKeys(this._keys);
  51393. }
  51394. if (this._ranges) {
  51395. clone._ranges = {};
  51396. for (var name in this._ranges) {
  51397. var range = this._ranges[name];
  51398. if (!range) {
  51399. continue;
  51400. }
  51401. clone._ranges[name] = range.clone();
  51402. }
  51403. }
  51404. return clone;
  51405. };
  51406. /**
  51407. * Sets the key frames of the animation
  51408. * @param values The animation key frames to set
  51409. */
  51410. Animation.prototype.setKeys = function (values) {
  51411. this._keys = values.slice(0);
  51412. };
  51413. /**
  51414. * Serializes the animation to an object
  51415. * @returns Serialized object
  51416. */
  51417. Animation.prototype.serialize = function () {
  51418. var serializationObject = {};
  51419. serializationObject.name = this.name;
  51420. serializationObject.property = this.targetProperty;
  51421. serializationObject.framePerSecond = this.framePerSecond;
  51422. serializationObject.dataType = this.dataType;
  51423. serializationObject.loopBehavior = this.loopMode;
  51424. serializationObject.enableBlending = this.enableBlending;
  51425. serializationObject.blendingSpeed = this.blendingSpeed;
  51426. var dataType = this.dataType;
  51427. serializationObject.keys = [];
  51428. var keys = this.getKeys();
  51429. for (var index = 0; index < keys.length; index++) {
  51430. var animationKey = keys[index];
  51431. var key = {};
  51432. key.frame = animationKey.frame;
  51433. switch (dataType) {
  51434. case Animation.ANIMATIONTYPE_FLOAT:
  51435. key.values = [animationKey.value];
  51436. break;
  51437. case Animation.ANIMATIONTYPE_QUATERNION:
  51438. case Animation.ANIMATIONTYPE_MATRIX:
  51439. case Animation.ANIMATIONTYPE_VECTOR3:
  51440. case Animation.ANIMATIONTYPE_COLOR3:
  51441. key.values = animationKey.value.asArray();
  51442. break;
  51443. }
  51444. serializationObject.keys.push(key);
  51445. }
  51446. serializationObject.ranges = [];
  51447. for (var name in this._ranges) {
  51448. var source = this._ranges[name];
  51449. if (!source) {
  51450. continue;
  51451. }
  51452. var range = {};
  51453. range.name = name;
  51454. range.from = source.from;
  51455. range.to = source.to;
  51456. serializationObject.ranges.push(range);
  51457. }
  51458. return serializationObject;
  51459. };
  51460. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51461. /**
  51462. * Get the float animation type
  51463. */
  51464. get: function () {
  51465. return Animation._ANIMATIONTYPE_FLOAT;
  51466. },
  51467. enumerable: true,
  51468. configurable: true
  51469. });
  51470. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51471. /**
  51472. * Get the Vector3 animation type
  51473. */
  51474. get: function () {
  51475. return Animation._ANIMATIONTYPE_VECTOR3;
  51476. },
  51477. enumerable: true,
  51478. configurable: true
  51479. });
  51480. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51481. /**
  51482. * Get the Vectpr2 animation type
  51483. */
  51484. get: function () {
  51485. return Animation._ANIMATIONTYPE_VECTOR2;
  51486. },
  51487. enumerable: true,
  51488. configurable: true
  51489. });
  51490. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51491. /**
  51492. * Get the Size animation type
  51493. */
  51494. get: function () {
  51495. return Animation._ANIMATIONTYPE_SIZE;
  51496. },
  51497. enumerable: true,
  51498. configurable: true
  51499. });
  51500. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51501. /**
  51502. * Get the Quaternion animation type
  51503. */
  51504. get: function () {
  51505. return Animation._ANIMATIONTYPE_QUATERNION;
  51506. },
  51507. enumerable: true,
  51508. configurable: true
  51509. });
  51510. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51511. /**
  51512. * Get the Matrix animation type
  51513. */
  51514. get: function () {
  51515. return Animation._ANIMATIONTYPE_MATRIX;
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51521. /**
  51522. * Get the Color3 animation type
  51523. */
  51524. get: function () {
  51525. return Animation._ANIMATIONTYPE_COLOR3;
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51531. /**
  51532. * Get the Relative Loop Mode
  51533. */
  51534. get: function () {
  51535. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51541. /**
  51542. * Get the Cycle Loop Mode
  51543. */
  51544. get: function () {
  51545. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51551. /**
  51552. * Get the Constant Loop Mode
  51553. */
  51554. get: function () {
  51555. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51556. },
  51557. enumerable: true,
  51558. configurable: true
  51559. });
  51560. /** @hidden */
  51561. Animation._UniversalLerp = function (left, right, amount) {
  51562. var constructor = left.constructor;
  51563. if (constructor.Lerp) { // Lerp supported
  51564. return constructor.Lerp(left, right, amount);
  51565. }
  51566. else if (constructor.Slerp) { // Slerp supported
  51567. return constructor.Slerp(left, right, amount);
  51568. }
  51569. else if (left.toFixed) { // Number
  51570. return left * (1.0 - amount) + amount * right;
  51571. }
  51572. else { // Blending not supported
  51573. return right;
  51574. }
  51575. };
  51576. /**
  51577. * Parses an animation object and creates an animation
  51578. * @param parsedAnimation Parsed animation object
  51579. * @returns Animation object
  51580. */
  51581. Animation.Parse = function (parsedAnimation) {
  51582. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51583. var dataType = parsedAnimation.dataType;
  51584. var keys = [];
  51585. var data;
  51586. var index;
  51587. if (parsedAnimation.enableBlending) {
  51588. animation.enableBlending = parsedAnimation.enableBlending;
  51589. }
  51590. if (parsedAnimation.blendingSpeed) {
  51591. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51592. }
  51593. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51594. var key = parsedAnimation.keys[index];
  51595. var inTangent;
  51596. var outTangent;
  51597. switch (dataType) {
  51598. case Animation.ANIMATIONTYPE_FLOAT:
  51599. data = key.values[0];
  51600. if (key.values.length >= 1) {
  51601. inTangent = key.values[1];
  51602. }
  51603. if (key.values.length >= 2) {
  51604. outTangent = key.values[2];
  51605. }
  51606. break;
  51607. case Animation.ANIMATIONTYPE_QUATERNION:
  51608. data = BABYLON.Quaternion.FromArray(key.values);
  51609. if (key.values.length >= 8) {
  51610. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51611. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51612. inTangent = _inTangent;
  51613. }
  51614. }
  51615. if (key.values.length >= 12) {
  51616. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51617. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51618. outTangent = _outTangent;
  51619. }
  51620. }
  51621. break;
  51622. case Animation.ANIMATIONTYPE_MATRIX:
  51623. data = BABYLON.Matrix.FromArray(key.values);
  51624. break;
  51625. case Animation.ANIMATIONTYPE_COLOR3:
  51626. data = BABYLON.Color3.FromArray(key.values);
  51627. break;
  51628. case Animation.ANIMATIONTYPE_VECTOR3:
  51629. default:
  51630. data = BABYLON.Vector3.FromArray(key.values);
  51631. break;
  51632. }
  51633. var keyData = {};
  51634. keyData.frame = key.frame;
  51635. keyData.value = data;
  51636. if (inTangent != undefined) {
  51637. keyData.inTangent = inTangent;
  51638. }
  51639. if (outTangent != undefined) {
  51640. keyData.outTangent = outTangent;
  51641. }
  51642. keys.push(keyData);
  51643. }
  51644. animation.setKeys(keys);
  51645. if (parsedAnimation.ranges) {
  51646. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51647. data = parsedAnimation.ranges[index];
  51648. animation.createRange(data.name, data.from, data.to);
  51649. }
  51650. }
  51651. return animation;
  51652. };
  51653. /**
  51654. * Appends the serialized animations from the source animations
  51655. * @param source Source containing the animations
  51656. * @param destination Target to store the animations
  51657. */
  51658. Animation.AppendSerializedAnimations = function (source, destination) {
  51659. if (source.animations) {
  51660. destination.animations = [];
  51661. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51662. var animation = source.animations[animationIndex];
  51663. destination.animations.push(animation.serialize());
  51664. }
  51665. }
  51666. };
  51667. /**
  51668. * Use matrix interpolation instead of using direct key value when animating matrices
  51669. */
  51670. Animation.AllowMatricesInterpolation = false;
  51671. /**
  51672. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51673. */
  51674. Animation.AllowMatrixDecomposeForInterpolation = true;
  51675. // Statics
  51676. /**
  51677. * Float animation type
  51678. */
  51679. Animation._ANIMATIONTYPE_FLOAT = 0;
  51680. /**
  51681. * Vector3 animation type
  51682. */
  51683. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51684. /**
  51685. * Quaternion animation type
  51686. */
  51687. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51688. /**
  51689. * Matrix animation type
  51690. */
  51691. Animation._ANIMATIONTYPE_MATRIX = 3;
  51692. /**
  51693. * Color3 animation type
  51694. */
  51695. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51696. /**
  51697. * Vector2 animation type
  51698. */
  51699. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51700. /**
  51701. * Size animation type
  51702. */
  51703. Animation._ANIMATIONTYPE_SIZE = 6;
  51704. /**
  51705. * Relative Loop Mode
  51706. */
  51707. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51708. /**
  51709. * Cycle Loop Mode
  51710. */
  51711. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51712. /**
  51713. * Constant Loop Mode
  51714. */
  51715. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51716. return Animation;
  51717. }());
  51718. BABYLON.Animation = Animation;
  51719. })(BABYLON || (BABYLON = {}));
  51720. //# sourceMappingURL=babylon.animation.js.map
  51721. var BABYLON;
  51722. (function (BABYLON) {
  51723. /**
  51724. * This class defines the direct association between an animation and a target
  51725. */
  51726. var TargetedAnimation = /** @class */ (function () {
  51727. function TargetedAnimation() {
  51728. }
  51729. return TargetedAnimation;
  51730. }());
  51731. BABYLON.TargetedAnimation = TargetedAnimation;
  51732. /**
  51733. * Use this class to create coordinated animations on multiple targets
  51734. */
  51735. var AnimationGroup = /** @class */ (function () {
  51736. function AnimationGroup(name, scene) {
  51737. if (scene === void 0) { scene = null; }
  51738. this.name = name;
  51739. this._targetedAnimations = new Array();
  51740. this._animatables = new Array();
  51741. this._from = Number.MAX_VALUE;
  51742. this._to = -Number.MAX_VALUE;
  51743. this._speedRatio = 1;
  51744. this.onAnimationEndObservable = new BABYLON.Observable();
  51745. /**
  51746. * This observable will notify when all animations have ended.
  51747. */
  51748. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51749. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51750. this._scene.animationGroups.push(this);
  51751. }
  51752. Object.defineProperty(AnimationGroup.prototype, "from", {
  51753. /**
  51754. * Gets the first frame
  51755. */
  51756. get: function () {
  51757. return this._from;
  51758. },
  51759. enumerable: true,
  51760. configurable: true
  51761. });
  51762. Object.defineProperty(AnimationGroup.prototype, "to", {
  51763. /**
  51764. * Gets the last frame
  51765. */
  51766. get: function () {
  51767. return this._to;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51773. /**
  51774. * Define if the animations are started
  51775. */
  51776. get: function () {
  51777. return this._isStarted;
  51778. },
  51779. enumerable: true,
  51780. configurable: true
  51781. });
  51782. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51783. /**
  51784. * Gets or sets the speed ratio to use for all animations
  51785. */
  51786. get: function () {
  51787. return this._speedRatio;
  51788. },
  51789. /**
  51790. * Gets or sets the speed ratio to use for all animations
  51791. */
  51792. set: function (value) {
  51793. if (this._speedRatio === value) {
  51794. return;
  51795. }
  51796. this._speedRatio = value;
  51797. for (var index = 0; index < this._animatables.length; index++) {
  51798. var animatable = this._animatables[index];
  51799. animatable.speedRatio = this._speedRatio;
  51800. }
  51801. },
  51802. enumerable: true,
  51803. configurable: true
  51804. });
  51805. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51806. /**
  51807. * Gets the targeted animations for this animation group
  51808. */
  51809. get: function () {
  51810. return this._targetedAnimations;
  51811. },
  51812. enumerable: true,
  51813. configurable: true
  51814. });
  51815. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51816. /**
  51817. * returning the list of animatables controlled by this animation group.
  51818. */
  51819. get: function () {
  51820. return this._animatables;
  51821. },
  51822. enumerable: true,
  51823. configurable: true
  51824. });
  51825. /**
  51826. * Add an animation (with its target) in the group
  51827. * @param animation defines the animation we want to add
  51828. * @param target defines the target of the animation
  51829. * @returns the {BABYLON.TargetedAnimation} object
  51830. */
  51831. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51832. var targetedAnimation = {
  51833. animation: animation,
  51834. target: target
  51835. };
  51836. var keys = animation.getKeys();
  51837. if (this._from > keys[0].frame) {
  51838. this._from = keys[0].frame;
  51839. }
  51840. if (this._to < keys[keys.length - 1].frame) {
  51841. this._to = keys[keys.length - 1].frame;
  51842. }
  51843. this._targetedAnimations.push(targetedAnimation);
  51844. return targetedAnimation;
  51845. };
  51846. /**
  51847. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51848. * It can add constant keys at begin or end
  51849. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51850. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51851. */
  51852. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51853. if (beginFrame === void 0) { beginFrame = null; }
  51854. if (endFrame === void 0) { endFrame = null; }
  51855. if (beginFrame == null)
  51856. beginFrame = this._from;
  51857. if (endFrame == null)
  51858. endFrame = this._to;
  51859. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51860. var targetedAnimation = this._targetedAnimations[index];
  51861. var keys = targetedAnimation.animation.getKeys();
  51862. var startKey = keys[0];
  51863. var endKey = keys[keys.length - 1];
  51864. if (startKey.frame > beginFrame) {
  51865. var newKey = {
  51866. frame: beginFrame,
  51867. value: startKey.value,
  51868. inTangent: startKey.inTangent,
  51869. outTangent: startKey.outTangent,
  51870. interpolation: startKey.interpolation
  51871. };
  51872. keys.splice(0, 0, newKey);
  51873. }
  51874. if (endKey.frame < endFrame) {
  51875. var newKey = {
  51876. frame: endFrame,
  51877. value: endKey.value,
  51878. inTangent: endKey.outTangent,
  51879. outTangent: endKey.outTangent,
  51880. interpolation: endKey.interpolation
  51881. };
  51882. keys.push(newKey);
  51883. }
  51884. }
  51885. this._from = beginFrame;
  51886. this._to = endFrame;
  51887. return this;
  51888. };
  51889. /**
  51890. * Start all animations on given targets
  51891. * @param loop defines if animations must loop
  51892. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51893. * @param from defines the from key (optional)
  51894. * @param to defines the to key (optional)
  51895. * @returns the current animation group
  51896. */
  51897. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51898. var _this = this;
  51899. if (loop === void 0) { loop = false; }
  51900. if (speedRatio === void 0) { speedRatio = 1; }
  51901. if (this._isStarted || this._targetedAnimations.length === 0) {
  51902. return this;
  51903. }
  51904. var _loop_1 = function (targetedAnimation) {
  51905. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51906. animatable.onAnimationEnd = function () {
  51907. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51908. _this._checkAnimationGroupEnded(animatable);
  51909. };
  51910. this_1._animatables.push(animatable);
  51911. };
  51912. var this_1 = this;
  51913. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51914. var targetedAnimation = _a[_i];
  51915. _loop_1(targetedAnimation);
  51916. }
  51917. this._speedRatio = speedRatio;
  51918. this._isStarted = true;
  51919. return this;
  51920. };
  51921. /**
  51922. * Pause all animations
  51923. */
  51924. AnimationGroup.prototype.pause = function () {
  51925. if (!this._isStarted) {
  51926. return this;
  51927. }
  51928. for (var index = 0; index < this._animatables.length; index++) {
  51929. var animatable = this._animatables[index];
  51930. animatable.pause();
  51931. }
  51932. return this;
  51933. };
  51934. /**
  51935. * Play all animations to initial state
  51936. * This function will start() the animations if they were not started or will restart() them if they were paused
  51937. * @param loop defines if animations must loop
  51938. */
  51939. AnimationGroup.prototype.play = function (loop) {
  51940. // only if all animatables are ready and exist
  51941. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51942. if (loop !== undefined) {
  51943. for (var index = 0; index < this._animatables.length; index++) {
  51944. var animatable = this._animatables[index];
  51945. animatable.loopAnimation = loop;
  51946. }
  51947. }
  51948. this.restart();
  51949. }
  51950. else {
  51951. this.stop();
  51952. this.start(loop, this._speedRatio);
  51953. }
  51954. return this;
  51955. };
  51956. /**
  51957. * Reset all animations to initial state
  51958. */
  51959. AnimationGroup.prototype.reset = function () {
  51960. if (!this._isStarted) {
  51961. return this;
  51962. }
  51963. for (var index = 0; index < this._animatables.length; index++) {
  51964. var animatable = this._animatables[index];
  51965. animatable.reset();
  51966. }
  51967. return this;
  51968. };
  51969. /**
  51970. * Restart animations from key 0
  51971. */
  51972. AnimationGroup.prototype.restart = function () {
  51973. if (!this._isStarted) {
  51974. return this;
  51975. }
  51976. for (var index = 0; index < this._animatables.length; index++) {
  51977. var animatable = this._animatables[index];
  51978. animatable.restart();
  51979. }
  51980. return this;
  51981. };
  51982. /**
  51983. * Stop all animations
  51984. */
  51985. AnimationGroup.prototype.stop = function () {
  51986. if (!this._isStarted) {
  51987. return this;
  51988. }
  51989. for (var index = 0; index < this._animatables.length; index++) {
  51990. var animatable = this._animatables[index];
  51991. animatable.stop();
  51992. }
  51993. this._isStarted = false;
  51994. return this;
  51995. };
  51996. /**
  51997. * Set animation weight for all animatables
  51998. * @param weight defines the weight to use
  51999. * @return the animationGroup
  52000. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52001. */
  52002. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52003. for (var index = 0; index < this._animatables.length; index++) {
  52004. var animatable = this._animatables[index];
  52005. animatable.weight = weight;
  52006. }
  52007. return this;
  52008. };
  52009. /**
  52010. * Synchronize and normalize all animatables with a source animatable
  52011. * @param root defines the root animatable to synchronize with
  52012. * @return the animationGroup
  52013. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52014. */
  52015. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52016. for (var index = 0; index < this._animatables.length; index++) {
  52017. var animatable = this._animatables[index];
  52018. animatable.syncWith(root);
  52019. }
  52020. return this;
  52021. };
  52022. /**
  52023. * Goes to a specific frame in this animation group
  52024. * @param frame the frame number to go to
  52025. * @return the animationGroup
  52026. */
  52027. AnimationGroup.prototype.goToFrame = function (frame) {
  52028. if (!this._isStarted) {
  52029. return this;
  52030. }
  52031. for (var index = 0; index < this._animatables.length; index++) {
  52032. var animatable = this._animatables[index];
  52033. animatable.goToFrame(frame);
  52034. }
  52035. return this;
  52036. };
  52037. /**
  52038. * Dispose all associated resources
  52039. */
  52040. AnimationGroup.prototype.dispose = function () {
  52041. this._targetedAnimations = [];
  52042. this._animatables = [];
  52043. var index = this._scene.animationGroups.indexOf(this);
  52044. if (index > -1) {
  52045. this._scene.animationGroups.splice(index, 1);
  52046. }
  52047. };
  52048. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52049. // animatable should be taken out of the array
  52050. var idx = this._animatables.indexOf(animatable);
  52051. if (idx > -1) {
  52052. this._animatables.splice(idx, 1);
  52053. }
  52054. // all animatables were removed? animation group ended!
  52055. if (this._animatables.length === 0) {
  52056. this._isStarted = false;
  52057. this.onAnimationGroupEndObservable.notifyObservers(this);
  52058. }
  52059. };
  52060. return AnimationGroup;
  52061. }());
  52062. BABYLON.AnimationGroup = AnimationGroup;
  52063. })(BABYLON || (BABYLON = {}));
  52064. //# sourceMappingURL=babylon.animationGroup.js.map
  52065. var BABYLON;
  52066. (function (BABYLON) {
  52067. /**
  52068. * Defines a runtime animation
  52069. */
  52070. var RuntimeAnimation = /** @class */ (function () {
  52071. /**
  52072. * Create a new RuntimeAnimation object
  52073. * @param target defines the target of the animation
  52074. * @param animation defines the source animation object
  52075. * @param scene defines the hosting scene
  52076. * @param host defines the initiating Animatable
  52077. */
  52078. function RuntimeAnimation(target, animation, scene, host) {
  52079. var _this = this;
  52080. this._events = new Array();
  52081. /**
  52082. * The current frame of the runtime animation
  52083. */
  52084. this._currentFrame = 0;
  52085. /**
  52086. * The original value of the runtime animation
  52087. */
  52088. this._originalValue = new Array();
  52089. /**
  52090. * The offsets cache of the runtime animation
  52091. */
  52092. this._offsetsCache = {};
  52093. /**
  52094. * The high limits cache of the runtime animation
  52095. */
  52096. this._highLimitsCache = {};
  52097. /**
  52098. * Specifies if the runtime animation has been stopped
  52099. */
  52100. this._stopped = false;
  52101. /**
  52102. * The blending factor of the runtime animation
  52103. */
  52104. this._blendingFactor = 0;
  52105. /**
  52106. * The target path of the runtime animation
  52107. */
  52108. this._targetPath = "";
  52109. /**
  52110. * The weight of the runtime animation
  52111. */
  52112. this._weight = 1.0;
  52113. /**
  52114. * The ratio offset of the runtime animation
  52115. */
  52116. this._ratioOffset = 0;
  52117. /**
  52118. * The previous delay of the runtime animation
  52119. */
  52120. this._previousDelay = 0;
  52121. /**
  52122. * The previous ratio of the runtime animation
  52123. */
  52124. this._previousRatio = 0;
  52125. this._animation = animation;
  52126. this._target = target;
  52127. this._scene = scene;
  52128. this._host = host;
  52129. animation._runtimeAnimations.push(this);
  52130. // Cloning events locally
  52131. var events = animation.getEvents();
  52132. if (events && events.length > 0) {
  52133. events.forEach(function (e) {
  52134. _this._events.push(e._clone());
  52135. });
  52136. }
  52137. }
  52138. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52139. /**
  52140. * Gets the current frame of the runtime animation
  52141. */
  52142. get: function () {
  52143. return this._currentFrame;
  52144. },
  52145. enumerable: true,
  52146. configurable: true
  52147. });
  52148. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52149. /**
  52150. * Gets the weight of the runtime animation
  52151. */
  52152. get: function () {
  52153. return this._weight;
  52154. },
  52155. enumerable: true,
  52156. configurable: true
  52157. });
  52158. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52159. /**
  52160. * Gets the current value of the runtime animation
  52161. */
  52162. get: function () {
  52163. return this._currentValue;
  52164. },
  52165. enumerable: true,
  52166. configurable: true
  52167. });
  52168. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52169. /**
  52170. * Gets the target path of the runtime animation
  52171. */
  52172. get: function () {
  52173. return this._targetPath;
  52174. },
  52175. enumerable: true,
  52176. configurable: true
  52177. });
  52178. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52179. /**
  52180. * Gets the actual target of the runtime animation
  52181. */
  52182. get: function () {
  52183. return this._activeTarget;
  52184. },
  52185. enumerable: true,
  52186. configurable: true
  52187. });
  52188. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52189. /**
  52190. * Gets the animation from the runtime animation
  52191. */
  52192. get: function () {
  52193. return this._animation;
  52194. },
  52195. enumerable: true,
  52196. configurable: true
  52197. });
  52198. /**
  52199. * Resets the runtime animation to the beginning
  52200. * @param restoreOriginal defines whether to restore the target property to the original value
  52201. */
  52202. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52203. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52204. if (restoreOriginal) {
  52205. if (this._target instanceof Array) {
  52206. var index = 0;
  52207. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52208. var target = _a[_i];
  52209. if (this._originalValue[index] !== undefined) {
  52210. this._setValue(target, this._originalValue[index], -1);
  52211. }
  52212. index++;
  52213. }
  52214. }
  52215. else {
  52216. if (this._originalValue[0] !== undefined) {
  52217. this._setValue(this._target, this._originalValue[0], -1);
  52218. }
  52219. }
  52220. }
  52221. this._offsetsCache = {};
  52222. this._highLimitsCache = {};
  52223. this._currentFrame = 0;
  52224. this._blendingFactor = 0;
  52225. this._originalValue = new Array();
  52226. // Events
  52227. for (var index = 0; index < this._events.length; index++) {
  52228. this._events[index].isDone = false;
  52229. }
  52230. };
  52231. /**
  52232. * Specifies if the runtime animation is stopped
  52233. * @returns Boolean specifying if the runtime animation is stopped
  52234. */
  52235. RuntimeAnimation.prototype.isStopped = function () {
  52236. return this._stopped;
  52237. };
  52238. /**
  52239. * Disposes of the runtime animation
  52240. */
  52241. RuntimeAnimation.prototype.dispose = function () {
  52242. var index = this._animation.runtimeAnimations.indexOf(this);
  52243. if (index > -1) {
  52244. this._animation.runtimeAnimations.splice(index, 1);
  52245. }
  52246. };
  52247. /**
  52248. * Interpolates the animation from the current frame
  52249. * @param currentFrame The frame to interpolate the animation to
  52250. * @param repeatCount The number of times that the animation should loop
  52251. * @param loopMode The type of looping mode to use
  52252. * @param offsetValue Animation offset value
  52253. * @param highLimitValue The high limit value
  52254. * @returns The interpolated value
  52255. */
  52256. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52257. this._currentFrame = currentFrame;
  52258. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52259. this._workValue = BABYLON.Matrix.Zero();
  52260. }
  52261. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52262. };
  52263. /**
  52264. * Apply the interpolated value to the target
  52265. * @param currentValue defines the value computed by the animation
  52266. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52267. */
  52268. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52269. if (weight === void 0) { weight = 1.0; }
  52270. if (this._target instanceof Array) {
  52271. var index = 0;
  52272. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52273. var target = _a[_i];
  52274. this._setValue(target, currentValue, weight, index);
  52275. index++;
  52276. }
  52277. }
  52278. else {
  52279. this._setValue(this._target, currentValue, weight);
  52280. }
  52281. };
  52282. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52283. if (targetIndex === void 0) { targetIndex = 0; }
  52284. // Set value
  52285. var path;
  52286. var destination;
  52287. var targetPropertyPath = this._animation.targetPropertyPath;
  52288. if (targetPropertyPath.length > 1) {
  52289. var property = target[targetPropertyPath[0]];
  52290. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52291. property = property[targetPropertyPath[index]];
  52292. }
  52293. path = targetPropertyPath[targetPropertyPath.length - 1];
  52294. destination = property;
  52295. }
  52296. else {
  52297. path = targetPropertyPath[0];
  52298. destination = target;
  52299. }
  52300. this._targetPath = path;
  52301. this._activeTarget = destination;
  52302. this._weight = weight;
  52303. if (this._originalValue[targetIndex] === undefined) {
  52304. var originalValue = void 0;
  52305. if (destination.getRestPose && path === "_matrix") { // For bones
  52306. originalValue = destination.getRestPose();
  52307. }
  52308. else {
  52309. originalValue = destination[path];
  52310. }
  52311. if (originalValue && originalValue.clone) {
  52312. this._originalValue[targetIndex] = originalValue.clone();
  52313. }
  52314. else {
  52315. this._originalValue[targetIndex] = originalValue;
  52316. }
  52317. }
  52318. // Blending
  52319. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52320. if (enableBlending && this._blendingFactor <= 1.0) {
  52321. if (!this._originalBlendValue) {
  52322. var originalValue = destination[path];
  52323. if (originalValue.clone) {
  52324. this._originalBlendValue = originalValue.clone();
  52325. }
  52326. else {
  52327. this._originalBlendValue = originalValue;
  52328. }
  52329. }
  52330. if (this._originalBlendValue.m) { // Matrix
  52331. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52332. if (this._currentValue) {
  52333. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52334. }
  52335. else {
  52336. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52337. }
  52338. }
  52339. else {
  52340. if (this._currentValue) {
  52341. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52342. }
  52343. else {
  52344. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52345. }
  52346. }
  52347. }
  52348. else {
  52349. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52350. }
  52351. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52352. this._blendingFactor += blendingSpeed;
  52353. }
  52354. else {
  52355. this._currentValue = currentValue;
  52356. }
  52357. if (weight !== -1.0) {
  52358. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52359. }
  52360. else {
  52361. destination[path] = this._currentValue;
  52362. }
  52363. if (target.markAsDirty) {
  52364. target.markAsDirty(this._animation.targetProperty);
  52365. }
  52366. };
  52367. /**
  52368. * Gets the loop pmode of the runtime animation
  52369. * @returns Loop Mode
  52370. */
  52371. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52372. if (this._target && this._target.animationPropertiesOverride) {
  52373. return this._target.animationPropertiesOverride.loopMode;
  52374. }
  52375. return this._animation.loopMode;
  52376. };
  52377. /**
  52378. * Move the current animation to a given frame
  52379. * @param frame defines the frame to move to
  52380. */
  52381. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52382. var keys = this._animation.getKeys();
  52383. if (frame < keys[0].frame) {
  52384. frame = keys[0].frame;
  52385. }
  52386. else if (frame > keys[keys.length - 1].frame) {
  52387. frame = keys[keys.length - 1].frame;
  52388. }
  52389. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52390. this.setValue(currentValue, -1);
  52391. };
  52392. /**
  52393. * @hidden Internal use only
  52394. */
  52395. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52396. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52397. this._ratioOffset = this._previousRatio - newRatio;
  52398. };
  52399. /**
  52400. * Execute the current animation
  52401. * @param delay defines the delay to add to the current frame
  52402. * @param from defines the lower bound of the animation range
  52403. * @param to defines the upper bound of the animation range
  52404. * @param loop defines if the current animation must loop
  52405. * @param speedRatio defines the current speed ratio
  52406. * @param weight defines the weight of the animation (default is -1 so no weight)
  52407. * @returns a boolean indicating if the animation has ended
  52408. */
  52409. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52410. if (weight === void 0) { weight = -1.0; }
  52411. var targetPropertyPath = this._animation.targetPropertyPath;
  52412. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52413. this._stopped = true;
  52414. return false;
  52415. }
  52416. var returnValue = true;
  52417. var keys = this._animation.getKeys();
  52418. // Adding a start key at frame 0 if missing
  52419. if (keys[0].frame !== 0) {
  52420. var newKey = { frame: 0, value: keys[0].value };
  52421. keys.splice(0, 0, newKey);
  52422. }
  52423. // Check limits
  52424. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52425. from = keys[0].frame;
  52426. }
  52427. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52428. to = keys[keys.length - 1].frame;
  52429. }
  52430. //to and from cannot be the same key
  52431. if (from === to) {
  52432. if (from > keys[0].frame) {
  52433. from--;
  52434. }
  52435. else if (to < keys[keys.length - 1].frame) {
  52436. to++;
  52437. }
  52438. }
  52439. // Compute ratio
  52440. var range = to - from;
  52441. var offsetValue;
  52442. // ratio represents the frame delta between from and to
  52443. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52444. var highLimitValue = 0;
  52445. this._previousDelay = delay;
  52446. this._previousRatio = ratio;
  52447. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52448. returnValue = false;
  52449. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52450. }
  52451. else {
  52452. // Get max value if required
  52453. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52454. var keyOffset = to.toString() + from.toString();
  52455. if (!this._offsetsCache[keyOffset]) {
  52456. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52457. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52458. switch (this._animation.dataType) {
  52459. // Float
  52460. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52461. this._offsetsCache[keyOffset] = toValue - fromValue;
  52462. break;
  52463. // Quaternion
  52464. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52465. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52466. break;
  52467. // Vector3
  52468. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52469. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52470. // Vector2
  52471. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52473. // Size
  52474. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52475. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52476. // Color3
  52477. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52478. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52479. default:
  52480. break;
  52481. }
  52482. this._highLimitsCache[keyOffset] = toValue;
  52483. }
  52484. highLimitValue = this._highLimitsCache[keyOffset];
  52485. offsetValue = this._offsetsCache[keyOffset];
  52486. }
  52487. }
  52488. if (offsetValue === undefined) {
  52489. switch (this._animation.dataType) {
  52490. // Float
  52491. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52492. offsetValue = 0;
  52493. break;
  52494. // Quaternion
  52495. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52496. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52497. break;
  52498. // Vector3
  52499. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52500. offsetValue = BABYLON.Vector3.Zero();
  52501. break;
  52502. // Vector2
  52503. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52504. offsetValue = BABYLON.Vector2.Zero();
  52505. break;
  52506. // Size
  52507. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52508. offsetValue = BABYLON.Size.Zero();
  52509. break;
  52510. // Color3
  52511. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52512. offsetValue = BABYLON.Color3.Black();
  52513. }
  52514. }
  52515. // Compute value
  52516. var repeatCount = (ratio / range) >> 0;
  52517. var currentFrame = returnValue ? from + ratio % range : to;
  52518. // Need to normalize?
  52519. if (this._host && this._host.syncRoot) {
  52520. var syncRoot = this._host.syncRoot;
  52521. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52522. currentFrame = from + (to - from) * hostNormalizedFrame;
  52523. }
  52524. // Reset events if looping
  52525. var events = this._events;
  52526. if (range > 0 && this.currentFrame > currentFrame ||
  52527. range < 0 && this.currentFrame < currentFrame) {
  52528. // Need to reset animation events
  52529. for (var index = 0; index < events.length; index++) {
  52530. if (!events[index].onlyOnce) {
  52531. // reset event, the animation is looping
  52532. events[index].isDone = false;
  52533. }
  52534. }
  52535. }
  52536. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52537. // Set value
  52538. this.setValue(currentValue, weight);
  52539. // Check events
  52540. for (var index = 0; index < events.length; index++) {
  52541. // Make sure current frame has passed event frame and that event frame is within the current range
  52542. // Also, handle both forward and reverse animations
  52543. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52544. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52545. var event = events[index];
  52546. if (!event.isDone) {
  52547. // If event should be done only once, remove it.
  52548. if (event.onlyOnce) {
  52549. events.splice(index, 1);
  52550. index--;
  52551. }
  52552. event.isDone = true;
  52553. event.action();
  52554. } // Don't do anything if the event has already be done.
  52555. }
  52556. }
  52557. if (!returnValue) {
  52558. this._stopped = true;
  52559. }
  52560. return returnValue;
  52561. };
  52562. return RuntimeAnimation;
  52563. }());
  52564. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52565. })(BABYLON || (BABYLON = {}));
  52566. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52567. var BABYLON;
  52568. (function (BABYLON) {
  52569. var Animatable = /** @class */ (function () {
  52570. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52571. if (fromFrame === void 0) { fromFrame = 0; }
  52572. if (toFrame === void 0) { toFrame = 100; }
  52573. if (loopAnimation === void 0) { loopAnimation = false; }
  52574. if (speedRatio === void 0) { speedRatio = 1.0; }
  52575. this.target = target;
  52576. this.fromFrame = fromFrame;
  52577. this.toFrame = toFrame;
  52578. this.loopAnimation = loopAnimation;
  52579. this.onAnimationEnd = onAnimationEnd;
  52580. this._localDelayOffset = null;
  52581. this._pausedDelay = null;
  52582. this._runtimeAnimations = new Array();
  52583. this._paused = false;
  52584. this._speedRatio = 1;
  52585. this._weight = -1.0;
  52586. this.animationStarted = false;
  52587. /**
  52588. * Observer raised when the animation ends
  52589. */
  52590. this.onAnimationEndObservable = new BABYLON.Observable();
  52591. this._scene = scene;
  52592. if (animations) {
  52593. this.appendAnimations(target, animations);
  52594. }
  52595. this._speedRatio = speedRatio;
  52596. scene._activeAnimatables.push(this);
  52597. }
  52598. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52599. /**
  52600. * Gets the root Animatable used to synchronize and normalize animations
  52601. */
  52602. get: function () {
  52603. return this._syncRoot;
  52604. },
  52605. enumerable: true,
  52606. configurable: true
  52607. });
  52608. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52609. /**
  52610. * Gets the current frame of the first RuntimeAnimation
  52611. * Used to synchronize Animatables
  52612. */
  52613. get: function () {
  52614. if (this._runtimeAnimations.length === 0) {
  52615. return 0;
  52616. }
  52617. return this._runtimeAnimations[0].currentFrame;
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. Object.defineProperty(Animatable.prototype, "weight", {
  52623. /**
  52624. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52625. */
  52626. get: function () {
  52627. return this._weight;
  52628. },
  52629. set: function (value) {
  52630. if (value === -1) { // -1 is ok and means no weight
  52631. this._weight = -1;
  52632. return;
  52633. }
  52634. // Else weight must be in [0, 1] range
  52635. this._weight = Math.min(Math.max(value, 0), 1.0);
  52636. },
  52637. enumerable: true,
  52638. configurable: true
  52639. });
  52640. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52641. /**
  52642. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52643. */
  52644. get: function () {
  52645. return this._speedRatio;
  52646. },
  52647. set: function (value) {
  52648. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52649. var animation = this._runtimeAnimations[index];
  52650. animation._prepareForSpeedRatioChange(value);
  52651. }
  52652. this._speedRatio = value;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. // Methods
  52658. /**
  52659. * Synchronize and normalize current Animatable with a source Animatable
  52660. * This is useful when using animation weights and when animations are not of the same length
  52661. * @param root defines the root Animatable to synchronize with
  52662. * @returns the current Animatable
  52663. */
  52664. Animatable.prototype.syncWith = function (root) {
  52665. this._syncRoot = root;
  52666. if (root) {
  52667. // Make sure this animatable will animate after the root
  52668. var index = this._scene._activeAnimatables.indexOf(this);
  52669. if (index > -1) {
  52670. this._scene._activeAnimatables.splice(index, 1);
  52671. this._scene._activeAnimatables.push(this);
  52672. }
  52673. }
  52674. return this;
  52675. };
  52676. Animatable.prototype.getAnimations = function () {
  52677. return this._runtimeAnimations;
  52678. };
  52679. Animatable.prototype.appendAnimations = function (target, animations) {
  52680. for (var index = 0; index < animations.length; index++) {
  52681. var animation = animations[index];
  52682. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52683. }
  52684. };
  52685. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52686. var runtimeAnimations = this._runtimeAnimations;
  52687. for (var index = 0; index < runtimeAnimations.length; index++) {
  52688. if (runtimeAnimations[index].animation.targetProperty === property) {
  52689. return runtimeAnimations[index].animation;
  52690. }
  52691. }
  52692. return null;
  52693. };
  52694. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52695. var runtimeAnimations = this._runtimeAnimations;
  52696. for (var index = 0; index < runtimeAnimations.length; index++) {
  52697. if (runtimeAnimations[index].animation.targetProperty === property) {
  52698. return runtimeAnimations[index];
  52699. }
  52700. }
  52701. return null;
  52702. };
  52703. Animatable.prototype.reset = function () {
  52704. var runtimeAnimations = this._runtimeAnimations;
  52705. for (var index = 0; index < runtimeAnimations.length; index++) {
  52706. runtimeAnimations[index].reset(true);
  52707. }
  52708. this._localDelayOffset = null;
  52709. this._pausedDelay = null;
  52710. };
  52711. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52712. var runtimeAnimations = this._runtimeAnimations;
  52713. for (var index = 0; index < runtimeAnimations.length; index++) {
  52714. runtimeAnimations[index].animation.enableBlending = true;
  52715. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52716. }
  52717. };
  52718. Animatable.prototype.disableBlending = function () {
  52719. var runtimeAnimations = this._runtimeAnimations;
  52720. for (var index = 0; index < runtimeAnimations.length; index++) {
  52721. runtimeAnimations[index].animation.enableBlending = false;
  52722. }
  52723. };
  52724. Animatable.prototype.goToFrame = function (frame) {
  52725. var runtimeAnimations = this._runtimeAnimations;
  52726. if (runtimeAnimations[0]) {
  52727. var fps = runtimeAnimations[0].animation.framePerSecond;
  52728. var currentFrame = runtimeAnimations[0].currentFrame;
  52729. var adjustTime = frame - currentFrame;
  52730. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52731. if (this._localDelayOffset === null) {
  52732. this._localDelayOffset = 0;
  52733. }
  52734. this._localDelayOffset -= delay;
  52735. }
  52736. for (var index = 0; index < runtimeAnimations.length; index++) {
  52737. runtimeAnimations[index].goToFrame(frame);
  52738. }
  52739. };
  52740. Animatable.prototype.pause = function () {
  52741. if (this._paused) {
  52742. return;
  52743. }
  52744. this._paused = true;
  52745. };
  52746. Animatable.prototype.restart = function () {
  52747. this._paused = false;
  52748. };
  52749. Animatable.prototype._raiseOnAnimationEnd = function () {
  52750. if (this.onAnimationEnd) {
  52751. this.onAnimationEnd();
  52752. }
  52753. this.onAnimationEndObservable.notifyObservers(this);
  52754. };
  52755. Animatable.prototype.stop = function (animationName) {
  52756. if (animationName) {
  52757. var idx = this._scene._activeAnimatables.indexOf(this);
  52758. if (idx > -1) {
  52759. var runtimeAnimations = this._runtimeAnimations;
  52760. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52761. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52762. continue;
  52763. }
  52764. runtimeAnimations[index].dispose();
  52765. runtimeAnimations.splice(index, 1);
  52766. }
  52767. if (runtimeAnimations.length == 0) {
  52768. this._scene._activeAnimatables.splice(idx, 1);
  52769. this._raiseOnAnimationEnd();
  52770. }
  52771. }
  52772. }
  52773. else {
  52774. var index = this._scene._activeAnimatables.indexOf(this);
  52775. if (index > -1) {
  52776. this._scene._activeAnimatables.splice(index, 1);
  52777. var runtimeAnimations = this._runtimeAnimations;
  52778. for (var index = 0; index < runtimeAnimations.length; index++) {
  52779. runtimeAnimations[index].dispose();
  52780. }
  52781. this._raiseOnAnimationEnd();
  52782. }
  52783. }
  52784. };
  52785. /**
  52786. * Wait asynchronously for the animation to end
  52787. * @returns a promise which will be fullfilled when the animation ends
  52788. */
  52789. Animatable.prototype.waitAsync = function () {
  52790. var _this = this;
  52791. return new Promise(function (resolve, reject) {
  52792. _this.onAnimationEndObservable.add(function () {
  52793. resolve(_this);
  52794. }, undefined, undefined, _this, true);
  52795. });
  52796. };
  52797. /** @hidden */
  52798. Animatable.prototype._animate = function (delay) {
  52799. if (this._paused) {
  52800. this.animationStarted = false;
  52801. if (this._pausedDelay === null) {
  52802. this._pausedDelay = delay;
  52803. }
  52804. return true;
  52805. }
  52806. if (this._localDelayOffset === null) {
  52807. this._localDelayOffset = delay;
  52808. this._pausedDelay = null;
  52809. }
  52810. else if (this._pausedDelay !== null) {
  52811. this._localDelayOffset += delay - this._pausedDelay;
  52812. this._pausedDelay = null;
  52813. }
  52814. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52815. return true;
  52816. }
  52817. // Animating
  52818. var running = false;
  52819. var runtimeAnimations = this._runtimeAnimations;
  52820. var index;
  52821. for (index = 0; index < runtimeAnimations.length; index++) {
  52822. var animation = runtimeAnimations[index];
  52823. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52824. running = running || isRunning;
  52825. }
  52826. this.animationStarted = running;
  52827. if (!running) {
  52828. // Remove from active animatables
  52829. index = this._scene._activeAnimatables.indexOf(this);
  52830. this._scene._activeAnimatables.splice(index, 1);
  52831. // Dispose all runtime animations
  52832. for (index = 0; index < runtimeAnimations.length; index++) {
  52833. runtimeAnimations[index].dispose();
  52834. }
  52835. this._raiseOnAnimationEnd();
  52836. this.onAnimationEnd = null;
  52837. this.onAnimationEndObservable.clear();
  52838. }
  52839. return running;
  52840. };
  52841. return Animatable;
  52842. }());
  52843. BABYLON.Animatable = Animatable;
  52844. })(BABYLON || (BABYLON = {}));
  52845. //# sourceMappingURL=babylon.animatable.js.map
  52846. var BABYLON;
  52847. (function (BABYLON) {
  52848. var EasingFunction = /** @class */ (function () {
  52849. function EasingFunction() {
  52850. // Properties
  52851. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52852. }
  52853. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52854. get: function () {
  52855. return EasingFunction._EASINGMODE_EASEIN;
  52856. },
  52857. enumerable: true,
  52858. configurable: true
  52859. });
  52860. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52861. get: function () {
  52862. return EasingFunction._EASINGMODE_EASEOUT;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52868. get: function () {
  52869. return EasingFunction._EASINGMODE_EASEINOUT;
  52870. },
  52871. enumerable: true,
  52872. configurable: true
  52873. });
  52874. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52875. var n = Math.min(Math.max(easingMode, 0), 2);
  52876. this._easingMode = n;
  52877. };
  52878. EasingFunction.prototype.getEasingMode = function () {
  52879. return this._easingMode;
  52880. };
  52881. EasingFunction.prototype.easeInCore = function (gradient) {
  52882. throw new Error('You must implement this method');
  52883. };
  52884. EasingFunction.prototype.ease = function (gradient) {
  52885. switch (this._easingMode) {
  52886. case EasingFunction.EASINGMODE_EASEIN:
  52887. return this.easeInCore(gradient);
  52888. case EasingFunction.EASINGMODE_EASEOUT:
  52889. return (1 - this.easeInCore(1 - gradient));
  52890. }
  52891. if (gradient >= 0.5) {
  52892. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52893. }
  52894. return (this.easeInCore(gradient * 2) * 0.5);
  52895. };
  52896. //Statics
  52897. EasingFunction._EASINGMODE_EASEIN = 0;
  52898. EasingFunction._EASINGMODE_EASEOUT = 1;
  52899. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52900. return EasingFunction;
  52901. }());
  52902. BABYLON.EasingFunction = EasingFunction;
  52903. var CircleEase = /** @class */ (function (_super) {
  52904. __extends(CircleEase, _super);
  52905. function CircleEase() {
  52906. return _super !== null && _super.apply(this, arguments) || this;
  52907. }
  52908. CircleEase.prototype.easeInCore = function (gradient) {
  52909. gradient = Math.max(0, Math.min(1, gradient));
  52910. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52911. };
  52912. return CircleEase;
  52913. }(EasingFunction));
  52914. BABYLON.CircleEase = CircleEase;
  52915. var BackEase = /** @class */ (function (_super) {
  52916. __extends(BackEase, _super);
  52917. function BackEase(amplitude) {
  52918. if (amplitude === void 0) { amplitude = 1; }
  52919. var _this = _super.call(this) || this;
  52920. _this.amplitude = amplitude;
  52921. return _this;
  52922. }
  52923. BackEase.prototype.easeInCore = function (gradient) {
  52924. var num = Math.max(0, this.amplitude);
  52925. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52926. };
  52927. return BackEase;
  52928. }(EasingFunction));
  52929. BABYLON.BackEase = BackEase;
  52930. var BounceEase = /** @class */ (function (_super) {
  52931. __extends(BounceEase, _super);
  52932. function BounceEase(bounces, bounciness) {
  52933. if (bounces === void 0) { bounces = 3; }
  52934. if (bounciness === void 0) { bounciness = 2; }
  52935. var _this = _super.call(this) || this;
  52936. _this.bounces = bounces;
  52937. _this.bounciness = bounciness;
  52938. return _this;
  52939. }
  52940. BounceEase.prototype.easeInCore = function (gradient) {
  52941. var y = Math.max(0.0, this.bounces);
  52942. var bounciness = this.bounciness;
  52943. if (bounciness <= 1.0) {
  52944. bounciness = 1.001;
  52945. }
  52946. var num9 = Math.pow(bounciness, y);
  52947. var num5 = 1.0 - bounciness;
  52948. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52949. var num15 = gradient * num4;
  52950. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52951. var num3 = Math.floor(num65);
  52952. var num13 = num3 + 1.0;
  52953. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52954. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52955. var num7 = (num8 + num12) * 0.5;
  52956. var num6 = gradient - num7;
  52957. var num2 = num7 - num8;
  52958. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52959. };
  52960. return BounceEase;
  52961. }(EasingFunction));
  52962. BABYLON.BounceEase = BounceEase;
  52963. var CubicEase = /** @class */ (function (_super) {
  52964. __extends(CubicEase, _super);
  52965. function CubicEase() {
  52966. return _super !== null && _super.apply(this, arguments) || this;
  52967. }
  52968. CubicEase.prototype.easeInCore = function (gradient) {
  52969. return (gradient * gradient * gradient);
  52970. };
  52971. return CubicEase;
  52972. }(EasingFunction));
  52973. BABYLON.CubicEase = CubicEase;
  52974. var ElasticEase = /** @class */ (function (_super) {
  52975. __extends(ElasticEase, _super);
  52976. function ElasticEase(oscillations, springiness) {
  52977. if (oscillations === void 0) { oscillations = 3; }
  52978. if (springiness === void 0) { springiness = 3; }
  52979. var _this = _super.call(this) || this;
  52980. _this.oscillations = oscillations;
  52981. _this.springiness = springiness;
  52982. return _this;
  52983. }
  52984. ElasticEase.prototype.easeInCore = function (gradient) {
  52985. var num2;
  52986. var num3 = Math.max(0.0, this.oscillations);
  52987. var num = Math.max(0.0, this.springiness);
  52988. if (num == 0) {
  52989. num2 = gradient;
  52990. }
  52991. else {
  52992. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52993. }
  52994. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52995. };
  52996. return ElasticEase;
  52997. }(EasingFunction));
  52998. BABYLON.ElasticEase = ElasticEase;
  52999. var ExponentialEase = /** @class */ (function (_super) {
  53000. __extends(ExponentialEase, _super);
  53001. function ExponentialEase(exponent) {
  53002. if (exponent === void 0) { exponent = 2; }
  53003. var _this = _super.call(this) || this;
  53004. _this.exponent = exponent;
  53005. return _this;
  53006. }
  53007. ExponentialEase.prototype.easeInCore = function (gradient) {
  53008. if (this.exponent <= 0) {
  53009. return gradient;
  53010. }
  53011. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53012. };
  53013. return ExponentialEase;
  53014. }(EasingFunction));
  53015. BABYLON.ExponentialEase = ExponentialEase;
  53016. var PowerEase = /** @class */ (function (_super) {
  53017. __extends(PowerEase, _super);
  53018. function PowerEase(power) {
  53019. if (power === void 0) { power = 2; }
  53020. var _this = _super.call(this) || this;
  53021. _this.power = power;
  53022. return _this;
  53023. }
  53024. PowerEase.prototype.easeInCore = function (gradient) {
  53025. var y = Math.max(0.0, this.power);
  53026. return Math.pow(gradient, y);
  53027. };
  53028. return PowerEase;
  53029. }(EasingFunction));
  53030. BABYLON.PowerEase = PowerEase;
  53031. var QuadraticEase = /** @class */ (function (_super) {
  53032. __extends(QuadraticEase, _super);
  53033. function QuadraticEase() {
  53034. return _super !== null && _super.apply(this, arguments) || this;
  53035. }
  53036. QuadraticEase.prototype.easeInCore = function (gradient) {
  53037. return (gradient * gradient);
  53038. };
  53039. return QuadraticEase;
  53040. }(EasingFunction));
  53041. BABYLON.QuadraticEase = QuadraticEase;
  53042. var QuarticEase = /** @class */ (function (_super) {
  53043. __extends(QuarticEase, _super);
  53044. function QuarticEase() {
  53045. return _super !== null && _super.apply(this, arguments) || this;
  53046. }
  53047. QuarticEase.prototype.easeInCore = function (gradient) {
  53048. return (gradient * gradient * gradient * gradient);
  53049. };
  53050. return QuarticEase;
  53051. }(EasingFunction));
  53052. BABYLON.QuarticEase = QuarticEase;
  53053. var QuinticEase = /** @class */ (function (_super) {
  53054. __extends(QuinticEase, _super);
  53055. function QuinticEase() {
  53056. return _super !== null && _super.apply(this, arguments) || this;
  53057. }
  53058. QuinticEase.prototype.easeInCore = function (gradient) {
  53059. return (gradient * gradient * gradient * gradient * gradient);
  53060. };
  53061. return QuinticEase;
  53062. }(EasingFunction));
  53063. BABYLON.QuinticEase = QuinticEase;
  53064. var SineEase = /** @class */ (function (_super) {
  53065. __extends(SineEase, _super);
  53066. function SineEase() {
  53067. return _super !== null && _super.apply(this, arguments) || this;
  53068. }
  53069. SineEase.prototype.easeInCore = function (gradient) {
  53070. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53071. };
  53072. return SineEase;
  53073. }(EasingFunction));
  53074. BABYLON.SineEase = SineEase;
  53075. var BezierCurveEase = /** @class */ (function (_super) {
  53076. __extends(BezierCurveEase, _super);
  53077. function BezierCurveEase(x1, y1, x2, y2) {
  53078. if (x1 === void 0) { x1 = 0; }
  53079. if (y1 === void 0) { y1 = 0; }
  53080. if (x2 === void 0) { x2 = 1; }
  53081. if (y2 === void 0) { y2 = 1; }
  53082. var _this = _super.call(this) || this;
  53083. _this.x1 = x1;
  53084. _this.y1 = y1;
  53085. _this.x2 = x2;
  53086. _this.y2 = y2;
  53087. return _this;
  53088. }
  53089. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53090. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53091. };
  53092. return BezierCurveEase;
  53093. }(EasingFunction));
  53094. BABYLON.BezierCurveEase = BezierCurveEase;
  53095. })(BABYLON || (BABYLON = {}));
  53096. //# sourceMappingURL=babylon.easing.js.map
  53097. var BABYLON;
  53098. (function (BABYLON) {
  53099. /**
  53100. * A Condition applied to an Action
  53101. */
  53102. var Condition = /** @class */ (function () {
  53103. /**
  53104. * Creates a new Condition
  53105. * @param actionManager the manager of the action the condition is applied to
  53106. */
  53107. function Condition(actionManager) {
  53108. this._actionManager = actionManager;
  53109. }
  53110. /**
  53111. * Check if the current condition is valid
  53112. * @returns a boolean
  53113. */
  53114. Condition.prototype.isValid = function () {
  53115. return true;
  53116. };
  53117. /**
  53118. * Internal only
  53119. * @hidden
  53120. */
  53121. Condition.prototype._getProperty = function (propertyPath) {
  53122. return this._actionManager._getProperty(propertyPath);
  53123. };
  53124. /**
  53125. * Internal only
  53126. * @hidden
  53127. */
  53128. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53129. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53130. };
  53131. /**
  53132. * Serialize placeholder for child classes
  53133. * @returns the serialized object
  53134. */
  53135. Condition.prototype.serialize = function () {
  53136. };
  53137. /**
  53138. * Internal only
  53139. * @hidden
  53140. */
  53141. Condition.prototype._serialize = function (serializedCondition) {
  53142. return {
  53143. type: 2,
  53144. children: [],
  53145. name: serializedCondition.name,
  53146. properties: serializedCondition.properties
  53147. };
  53148. };
  53149. return Condition;
  53150. }());
  53151. BABYLON.Condition = Condition;
  53152. /**
  53153. * Defines specific conditional operators as extensions of Condition
  53154. */
  53155. var ValueCondition = /** @class */ (function (_super) {
  53156. __extends(ValueCondition, _super);
  53157. /**
  53158. * Creates a new ValueCondition
  53159. * @param actionManager manager for the action the condition applies to
  53160. * @param target for the action
  53161. * @param propertyPath path to specify the property of the target the conditional operator uses
  53162. * @param value the value compared by the conditional operator against the current value of the property
  53163. * @param operator the conditional operator, default ValueCondition.IsEqual
  53164. */
  53165. function ValueCondition(actionManager, target,
  53166. /** path to specify the property of the target the conditional operator uses */
  53167. propertyPath,
  53168. /** the value compared by the conditional operator against the current value of the property */
  53169. value,
  53170. /** the conditional operator, default ValueCondition.IsEqual */
  53171. operator) {
  53172. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53173. var _this = _super.call(this, actionManager) || this;
  53174. _this.propertyPath = propertyPath;
  53175. _this.value = value;
  53176. _this.operator = operator;
  53177. _this._target = target;
  53178. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53179. _this._property = _this._getProperty(_this.propertyPath);
  53180. return _this;
  53181. }
  53182. Object.defineProperty(ValueCondition, "IsEqual", {
  53183. /**
  53184. * returns the number for IsEqual
  53185. */
  53186. get: function () {
  53187. return ValueCondition._IsEqual;
  53188. },
  53189. enumerable: true,
  53190. configurable: true
  53191. });
  53192. Object.defineProperty(ValueCondition, "IsDifferent", {
  53193. /**
  53194. * Returns the number for IsDifferent
  53195. */
  53196. get: function () {
  53197. return ValueCondition._IsDifferent;
  53198. },
  53199. enumerable: true,
  53200. configurable: true
  53201. });
  53202. Object.defineProperty(ValueCondition, "IsGreater", {
  53203. /**
  53204. * Returns the number for IsGreater
  53205. */
  53206. get: function () {
  53207. return ValueCondition._IsGreater;
  53208. },
  53209. enumerable: true,
  53210. configurable: true
  53211. });
  53212. Object.defineProperty(ValueCondition, "IsLesser", {
  53213. /**
  53214. * Returns the number for IsLesser
  53215. */
  53216. get: function () {
  53217. return ValueCondition._IsLesser;
  53218. },
  53219. enumerable: true,
  53220. configurable: true
  53221. });
  53222. /**
  53223. * Compares the given value with the property value for the specified conditional operator
  53224. * @returns the result of the comparison
  53225. */
  53226. ValueCondition.prototype.isValid = function () {
  53227. switch (this.operator) {
  53228. case ValueCondition.IsGreater:
  53229. return this._effectiveTarget[this._property] > this.value;
  53230. case ValueCondition.IsLesser:
  53231. return this._effectiveTarget[this._property] < this.value;
  53232. case ValueCondition.IsEqual:
  53233. case ValueCondition.IsDifferent:
  53234. var check;
  53235. if (this.value.equals) {
  53236. check = this.value.equals(this._effectiveTarget[this._property]);
  53237. }
  53238. else {
  53239. check = this.value === this._effectiveTarget[this._property];
  53240. }
  53241. return this.operator === ValueCondition.IsEqual ? check : !check;
  53242. }
  53243. return false;
  53244. };
  53245. /**
  53246. * Serialize the ValueCondition into a JSON compatible object
  53247. * @returns serialization object
  53248. */
  53249. ValueCondition.prototype.serialize = function () {
  53250. return this._serialize({
  53251. name: "ValueCondition",
  53252. properties: [
  53253. BABYLON.Action._GetTargetProperty(this._target),
  53254. { name: "propertyPath", value: this.propertyPath },
  53255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53256. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53257. ]
  53258. });
  53259. };
  53260. /**
  53261. * Gets the name of the conditional operator for the ValueCondition
  53262. * @param operator the conditional operator
  53263. * @returns the name
  53264. */
  53265. ValueCondition.GetOperatorName = function (operator) {
  53266. switch (operator) {
  53267. case ValueCondition._IsEqual: return "IsEqual";
  53268. case ValueCondition._IsDifferent: return "IsDifferent";
  53269. case ValueCondition._IsGreater: return "IsGreater";
  53270. case ValueCondition._IsLesser: return "IsLesser";
  53271. default: return "";
  53272. }
  53273. };
  53274. /**
  53275. * Internal only
  53276. * @hidden
  53277. */
  53278. ValueCondition._IsEqual = 0;
  53279. /**
  53280. * Internal only
  53281. * @hidden
  53282. */
  53283. ValueCondition._IsDifferent = 1;
  53284. /**
  53285. * Internal only
  53286. * @hidden
  53287. */
  53288. ValueCondition._IsGreater = 2;
  53289. /**
  53290. * Internal only
  53291. * @hidden
  53292. */
  53293. ValueCondition._IsLesser = 3;
  53294. return ValueCondition;
  53295. }(Condition));
  53296. BABYLON.ValueCondition = ValueCondition;
  53297. /**
  53298. * Defines a predicate condition as an extension of Condition
  53299. */
  53300. var PredicateCondition = /** @class */ (function (_super) {
  53301. __extends(PredicateCondition, _super);
  53302. /**
  53303. * Creates a new PredicateCondition
  53304. * @param actionManager manager for the action the condition applies to
  53305. * @param predicate defines the predicate function used to validate the condition
  53306. */
  53307. function PredicateCondition(actionManager,
  53308. /** defines the predicate function used to validate the condition */
  53309. predicate) {
  53310. var _this = _super.call(this, actionManager) || this;
  53311. _this.predicate = predicate;
  53312. return _this;
  53313. }
  53314. /**
  53315. * @returns the validity of the predicate condition
  53316. */
  53317. PredicateCondition.prototype.isValid = function () {
  53318. return this.predicate();
  53319. };
  53320. return PredicateCondition;
  53321. }(Condition));
  53322. BABYLON.PredicateCondition = PredicateCondition;
  53323. /**
  53324. * Defines a state condition as an extension of Condition
  53325. */
  53326. var StateCondition = /** @class */ (function (_super) {
  53327. __extends(StateCondition, _super);
  53328. /**
  53329. * Creates a new StateCondition
  53330. * @param actionManager manager for the action the condition applies to
  53331. * @param target of the condition
  53332. * @param value to compare with target state
  53333. */
  53334. function StateCondition(actionManager, target, value) {
  53335. var _this = _super.call(this, actionManager) || this;
  53336. _this.value = value;
  53337. _this._target = target;
  53338. return _this;
  53339. }
  53340. /**
  53341. * @returns the validity of the state
  53342. */
  53343. StateCondition.prototype.isValid = function () {
  53344. return this._target.state === this.value;
  53345. };
  53346. /**
  53347. * Serialize the StateCondition into a JSON compatible object
  53348. * @returns serialization object
  53349. */
  53350. StateCondition.prototype.serialize = function () {
  53351. return this._serialize({
  53352. name: "StateCondition",
  53353. properties: [
  53354. BABYLON.Action._GetTargetProperty(this._target),
  53355. { name: "value", value: this.value }
  53356. ]
  53357. });
  53358. };
  53359. return StateCondition;
  53360. }(Condition));
  53361. BABYLON.StateCondition = StateCondition;
  53362. })(BABYLON || (BABYLON = {}));
  53363. //# sourceMappingURL=babylon.condition.js.map
  53364. var BABYLON;
  53365. (function (BABYLON) {
  53366. /**
  53367. * The action to be carried out following a trigger
  53368. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53369. */
  53370. var Action = /** @class */ (function () {
  53371. /**
  53372. * Creates a new Action
  53373. * @param triggerOptions the trigger, with or without parameters, for the action
  53374. * @param condition an optional determinant of action
  53375. */
  53376. function Action(
  53377. /** the trigger, with or without parameters, for the action */
  53378. triggerOptions, condition) {
  53379. this.triggerOptions = triggerOptions;
  53380. /**
  53381. * An event triggered prior to action being executed.
  53382. */
  53383. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53384. if (triggerOptions.parameter) {
  53385. this.trigger = triggerOptions.trigger;
  53386. this._triggerParameter = triggerOptions.parameter;
  53387. }
  53388. else {
  53389. this.trigger = triggerOptions;
  53390. }
  53391. this._nextActiveAction = this;
  53392. this._condition = condition;
  53393. }
  53394. /**
  53395. * Internal only
  53396. * @hidden
  53397. */
  53398. Action.prototype._prepare = function () {
  53399. };
  53400. /**
  53401. * Gets the trigger parameters
  53402. * @returns the trigger parameters
  53403. */
  53404. Action.prototype.getTriggerParameter = function () {
  53405. return this._triggerParameter;
  53406. };
  53407. /**
  53408. * Internal only - executes current action event
  53409. * @hidden
  53410. */
  53411. Action.prototype._executeCurrent = function (evt) {
  53412. if (this._nextActiveAction._condition) {
  53413. var condition = this._nextActiveAction._condition;
  53414. var currentRenderId = this._actionManager.getScene().getRenderId();
  53415. // We cache the current evaluation for the current frame
  53416. if (condition._evaluationId === currentRenderId) {
  53417. if (!condition._currentResult) {
  53418. return;
  53419. }
  53420. }
  53421. else {
  53422. condition._evaluationId = currentRenderId;
  53423. if (!condition.isValid()) {
  53424. condition._currentResult = false;
  53425. return;
  53426. }
  53427. condition._currentResult = true;
  53428. }
  53429. }
  53430. this.onBeforeExecuteObservable.notifyObservers(this);
  53431. this._nextActiveAction.execute(evt);
  53432. this.skipToNextActiveAction();
  53433. };
  53434. /**
  53435. * Execute placeholder for child classes
  53436. * @param evt optional action event
  53437. */
  53438. Action.prototype.execute = function (evt) {
  53439. };
  53440. /**
  53441. * Skips to next active action
  53442. */
  53443. Action.prototype.skipToNextActiveAction = function () {
  53444. if (this._nextActiveAction._child) {
  53445. if (!this._nextActiveAction._child._actionManager) {
  53446. this._nextActiveAction._child._actionManager = this._actionManager;
  53447. }
  53448. this._nextActiveAction = this._nextActiveAction._child;
  53449. }
  53450. else {
  53451. this._nextActiveAction = this;
  53452. }
  53453. };
  53454. /**
  53455. * Adds action to chain of actions, may be a DoNothingAction
  53456. * @param action defines the next action to execute
  53457. * @returns The action passed in
  53458. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53459. */
  53460. Action.prototype.then = function (action) {
  53461. this._child = action;
  53462. action._actionManager = this._actionManager;
  53463. action._prepare();
  53464. return action;
  53465. };
  53466. /**
  53467. * Internal only
  53468. * @hidden
  53469. */
  53470. Action.prototype._getProperty = function (propertyPath) {
  53471. return this._actionManager._getProperty(propertyPath);
  53472. };
  53473. /**
  53474. * Internal only
  53475. * @hidden
  53476. */
  53477. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53478. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53479. };
  53480. /**
  53481. * Serialize placeholder for child classes
  53482. * @param parent of child
  53483. * @returns the serialized object
  53484. */
  53485. Action.prototype.serialize = function (parent) {
  53486. };
  53487. /**
  53488. * Internal only called by serialize
  53489. * @hidden
  53490. */
  53491. Action.prototype._serialize = function (serializedAction, parent) {
  53492. var serializationObject = {
  53493. type: 1,
  53494. children: [],
  53495. name: serializedAction.name,
  53496. properties: serializedAction.properties || []
  53497. };
  53498. // Serialize child
  53499. if (this._child) {
  53500. this._child.serialize(serializationObject);
  53501. }
  53502. // Check if "this" has a condition
  53503. if (this._condition) {
  53504. var serializedCondition = this._condition.serialize();
  53505. serializedCondition.children.push(serializationObject);
  53506. if (parent) {
  53507. parent.children.push(serializedCondition);
  53508. }
  53509. return serializedCondition;
  53510. }
  53511. if (parent) {
  53512. parent.children.push(serializationObject);
  53513. }
  53514. return serializationObject;
  53515. };
  53516. /**
  53517. * Internal only
  53518. * @hidden
  53519. */
  53520. Action._SerializeValueAsString = function (value) {
  53521. if (typeof value === "number") {
  53522. return value.toString();
  53523. }
  53524. if (typeof value === "boolean") {
  53525. return value ? "true" : "false";
  53526. }
  53527. if (value instanceof BABYLON.Vector2) {
  53528. return value.x + ", " + value.y;
  53529. }
  53530. if (value instanceof BABYLON.Vector3) {
  53531. return value.x + ", " + value.y + ", " + value.z;
  53532. }
  53533. if (value instanceof BABYLON.Color3) {
  53534. return value.r + ", " + value.g + ", " + value.b;
  53535. }
  53536. if (value instanceof BABYLON.Color4) {
  53537. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53538. }
  53539. return value; // string
  53540. };
  53541. /**
  53542. * Internal only
  53543. * @hidden
  53544. */
  53545. Action._GetTargetProperty = function (target) {
  53546. return {
  53547. name: "target",
  53548. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53549. : target instanceof BABYLON.Light ? "LightProperties"
  53550. : target instanceof BABYLON.Camera ? "CameraProperties"
  53551. : "SceneProperties",
  53552. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53553. };
  53554. };
  53555. return Action;
  53556. }());
  53557. BABYLON.Action = Action;
  53558. })(BABYLON || (BABYLON = {}));
  53559. //# sourceMappingURL=babylon.action.js.map
  53560. var BABYLON;
  53561. (function (BABYLON) {
  53562. /**
  53563. * ActionEvent is the event being sent when an action is triggered.
  53564. */
  53565. var ActionEvent = /** @class */ (function () {
  53566. /**
  53567. * Creates a new ActionEvent
  53568. * @param source The mesh or sprite that triggered the action
  53569. * @param pointerX The X mouse cursor position at the time of the event
  53570. * @param pointerY The Y mouse cursor position at the time of the event
  53571. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53572. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53573. * @param additionalData additional data for the event
  53574. */
  53575. function ActionEvent(
  53576. /** The mesh or sprite that triggered the action */
  53577. source,
  53578. /** The X mouse cursor position at the time of the event */
  53579. pointerX,
  53580. /** The Y mouse cursor position at the time of the event */
  53581. pointerY,
  53582. /** The mesh that is currently pointed at (can be null) */
  53583. meshUnderPointer,
  53584. /** the original (browser) event that triggered the ActionEvent */
  53585. sourceEvent,
  53586. /** additional data for the event */
  53587. additionalData) {
  53588. this.source = source;
  53589. this.pointerX = pointerX;
  53590. this.pointerY = pointerY;
  53591. this.meshUnderPointer = meshUnderPointer;
  53592. this.sourceEvent = sourceEvent;
  53593. this.additionalData = additionalData;
  53594. }
  53595. /**
  53596. * Helper function to auto-create an ActionEvent from a source mesh.
  53597. * @param source The source mesh that triggered the event
  53598. * @param evt The original (browser) event
  53599. * @param additionalData additional data for the event
  53600. * @returns the new ActionEvent
  53601. */
  53602. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53603. var scene = source.getScene();
  53604. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53605. };
  53606. /**
  53607. * Helper function to auto-create an ActionEvent from a source sprite
  53608. * @param source The source sprite that triggered the event
  53609. * @param scene Scene associated with the sprite
  53610. * @param evt The original (browser) event
  53611. * @param additionalData additional data for the event
  53612. * @returns the new ActionEvent
  53613. */
  53614. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53615. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53616. };
  53617. /**
  53618. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53619. * @param scene the scene where the event occurred
  53620. * @param evt The original (browser) event
  53621. * @returns the new ActionEvent
  53622. */
  53623. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53624. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53625. };
  53626. /**
  53627. * Helper function to auto-create an ActionEvent from a primitive
  53628. * @param prim defines the target primitive
  53629. * @param pointerPos defines the pointer position
  53630. * @param evt The original (browser) event
  53631. * @param additionalData additional data for the event
  53632. * @returns the new ActionEvent
  53633. */
  53634. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53635. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53636. };
  53637. return ActionEvent;
  53638. }());
  53639. BABYLON.ActionEvent = ActionEvent;
  53640. /**
  53641. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53642. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53643. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53644. */
  53645. var ActionManager = /** @class */ (function () {
  53646. /**
  53647. * Creates a new action manager
  53648. * @param scene defines the hosting scene
  53649. */
  53650. function ActionManager(scene) {
  53651. // Members
  53652. /** Gets the list of actions */
  53653. this.actions = new Array();
  53654. /** Gets the cursor to use when hovering items */
  53655. this.hoverCursor = '';
  53656. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53657. scene._actionManagers.push(this);
  53658. }
  53659. Object.defineProperty(ActionManager, "NothingTrigger", {
  53660. /**
  53661. * Nothing
  53662. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53663. */
  53664. get: function () {
  53665. return ActionManager._NothingTrigger;
  53666. },
  53667. enumerable: true,
  53668. configurable: true
  53669. });
  53670. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53671. /**
  53672. * On pick
  53673. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53674. */
  53675. get: function () {
  53676. return ActionManager._OnPickTrigger;
  53677. },
  53678. enumerable: true,
  53679. configurable: true
  53680. });
  53681. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53682. /**
  53683. * On left pick
  53684. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53685. */
  53686. get: function () {
  53687. return ActionManager._OnLeftPickTrigger;
  53688. },
  53689. enumerable: true,
  53690. configurable: true
  53691. });
  53692. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53693. /**
  53694. * On right pick
  53695. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53696. */
  53697. get: function () {
  53698. return ActionManager._OnRightPickTrigger;
  53699. },
  53700. enumerable: true,
  53701. configurable: true
  53702. });
  53703. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53704. /**
  53705. * On center pick
  53706. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53707. */
  53708. get: function () {
  53709. return ActionManager._OnCenterPickTrigger;
  53710. },
  53711. enumerable: true,
  53712. configurable: true
  53713. });
  53714. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53715. /**
  53716. * On pick down
  53717. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53718. */
  53719. get: function () {
  53720. return ActionManager._OnPickDownTrigger;
  53721. },
  53722. enumerable: true,
  53723. configurable: true
  53724. });
  53725. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53726. /**
  53727. * On double pick
  53728. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53729. */
  53730. get: function () {
  53731. return ActionManager._OnDoublePickTrigger;
  53732. },
  53733. enumerable: true,
  53734. configurable: true
  53735. });
  53736. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53737. /**
  53738. * On pick up
  53739. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53740. */
  53741. get: function () {
  53742. return ActionManager._OnPickUpTrigger;
  53743. },
  53744. enumerable: true,
  53745. configurable: true
  53746. });
  53747. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53748. /**
  53749. * On pick out.
  53750. * This trigger will only be raised if you also declared a OnPickDown
  53751. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53752. */
  53753. get: function () {
  53754. return ActionManager._OnPickOutTrigger;
  53755. },
  53756. enumerable: true,
  53757. configurable: true
  53758. });
  53759. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53760. /**
  53761. * On long press
  53762. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53763. */
  53764. get: function () {
  53765. return ActionManager._OnLongPressTrigger;
  53766. },
  53767. enumerable: true,
  53768. configurable: true
  53769. });
  53770. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53771. /**
  53772. * On pointer over
  53773. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53774. */
  53775. get: function () {
  53776. return ActionManager._OnPointerOverTrigger;
  53777. },
  53778. enumerable: true,
  53779. configurable: true
  53780. });
  53781. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53782. /**
  53783. * On pointer out
  53784. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53785. */
  53786. get: function () {
  53787. return ActionManager._OnPointerOutTrigger;
  53788. },
  53789. enumerable: true,
  53790. configurable: true
  53791. });
  53792. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53793. /**
  53794. * On every frame
  53795. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53796. */
  53797. get: function () {
  53798. return ActionManager._OnEveryFrameTrigger;
  53799. },
  53800. enumerable: true,
  53801. configurable: true
  53802. });
  53803. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53804. /**
  53805. * On intersection enter
  53806. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53807. */
  53808. get: function () {
  53809. return ActionManager._OnIntersectionEnterTrigger;
  53810. },
  53811. enumerable: true,
  53812. configurable: true
  53813. });
  53814. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53815. /**
  53816. * On intersection exit
  53817. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53818. */
  53819. get: function () {
  53820. return ActionManager._OnIntersectionExitTrigger;
  53821. },
  53822. enumerable: true,
  53823. configurable: true
  53824. });
  53825. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53826. /**
  53827. * On key down
  53828. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53829. */
  53830. get: function () {
  53831. return ActionManager._OnKeyDownTrigger;
  53832. },
  53833. enumerable: true,
  53834. configurable: true
  53835. });
  53836. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53837. /**
  53838. * On key up
  53839. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53840. */
  53841. get: function () {
  53842. return ActionManager._OnKeyUpTrigger;
  53843. },
  53844. enumerable: true,
  53845. configurable: true
  53846. });
  53847. // Methods
  53848. /**
  53849. * Releases all associated resources
  53850. */
  53851. ActionManager.prototype.dispose = function () {
  53852. var index = this._scene._actionManagers.indexOf(this);
  53853. for (var i = 0; i < this.actions.length; i++) {
  53854. var action = this.actions[i];
  53855. ActionManager.Triggers[action.trigger]--;
  53856. if (ActionManager.Triggers[action.trigger] === 0) {
  53857. delete ActionManager.Triggers[action.trigger];
  53858. }
  53859. }
  53860. if (index > -1) {
  53861. this._scene._actionManagers.splice(index, 1);
  53862. }
  53863. };
  53864. /**
  53865. * Gets hosting scene
  53866. * @returns the hosting scene
  53867. */
  53868. ActionManager.prototype.getScene = function () {
  53869. return this._scene;
  53870. };
  53871. /**
  53872. * Does this action manager handles actions of any of the given triggers
  53873. * @param triggers defines the triggers to be tested
  53874. * @return a boolean indicating whether one (or more) of the triggers is handled
  53875. */
  53876. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53877. for (var index = 0; index < this.actions.length; index++) {
  53878. var action = this.actions[index];
  53879. if (triggers.indexOf(action.trigger) > -1) {
  53880. return true;
  53881. }
  53882. }
  53883. return false;
  53884. };
  53885. /**
  53886. * Does this action manager handles actions of a given trigger
  53887. * @param trigger defines the trigger to be tested
  53888. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53889. * @return whether the trigger is handled
  53890. */
  53891. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53892. for (var index = 0; index < this.actions.length; index++) {
  53893. var action = this.actions[index];
  53894. if (action.trigger === trigger) {
  53895. if (parameterPredicate) {
  53896. if (parameterPredicate(action.getTriggerParameter())) {
  53897. return true;
  53898. }
  53899. }
  53900. else {
  53901. return true;
  53902. }
  53903. }
  53904. }
  53905. return false;
  53906. };
  53907. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53908. /**
  53909. * Does this action manager has pointer triggers
  53910. */
  53911. get: function () {
  53912. for (var index = 0; index < this.actions.length; index++) {
  53913. var action = this.actions[index];
  53914. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53915. return true;
  53916. }
  53917. }
  53918. return false;
  53919. },
  53920. enumerable: true,
  53921. configurable: true
  53922. });
  53923. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53924. /**
  53925. * Does this action manager has pick triggers
  53926. */
  53927. get: function () {
  53928. for (var index = 0; index < this.actions.length; index++) {
  53929. var action = this.actions[index];
  53930. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53931. return true;
  53932. }
  53933. }
  53934. return false;
  53935. },
  53936. enumerable: true,
  53937. configurable: true
  53938. });
  53939. Object.defineProperty(ActionManager, "HasTriggers", {
  53940. /**
  53941. * Does exist one action manager with at least one trigger
  53942. **/
  53943. get: function () {
  53944. for (var t in ActionManager.Triggers) {
  53945. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53946. return true;
  53947. }
  53948. }
  53949. return false;
  53950. },
  53951. enumerable: true,
  53952. configurable: true
  53953. });
  53954. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53955. /**
  53956. * Does exist one action manager with at least one pick trigger
  53957. **/
  53958. get: function () {
  53959. for (var t in ActionManager.Triggers) {
  53960. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53961. var t_int = parseInt(t);
  53962. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53963. return true;
  53964. }
  53965. }
  53966. }
  53967. return false;
  53968. },
  53969. enumerable: true,
  53970. configurable: true
  53971. });
  53972. /**
  53973. * Does exist one action manager that handles actions of a given trigger
  53974. * @param trigger defines the trigger to be tested
  53975. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53976. **/
  53977. ActionManager.HasSpecificTrigger = function (trigger) {
  53978. for (var t in ActionManager.Triggers) {
  53979. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53980. var t_int = parseInt(t);
  53981. if (t_int === trigger) {
  53982. return true;
  53983. }
  53984. }
  53985. }
  53986. return false;
  53987. };
  53988. /**
  53989. * Registers an action to this action manager
  53990. * @param action defines the action to be registered
  53991. * @return the action amended (prepared) after registration
  53992. */
  53993. ActionManager.prototype.registerAction = function (action) {
  53994. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53995. if (this.getScene().actionManager !== this) {
  53996. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53997. return null;
  53998. }
  53999. }
  54000. this.actions.push(action);
  54001. if (ActionManager.Triggers[action.trigger]) {
  54002. ActionManager.Triggers[action.trigger]++;
  54003. }
  54004. else {
  54005. ActionManager.Triggers[action.trigger] = 1;
  54006. }
  54007. action._actionManager = this;
  54008. action._prepare();
  54009. return action;
  54010. };
  54011. /**
  54012. * Unregisters an action to this action manager
  54013. * @param action defines the action to be unregistered
  54014. * @return a boolean indicating whether the action has been unregistered
  54015. */
  54016. ActionManager.prototype.unregisterAction = function (action) {
  54017. var index = this.actions.indexOf(action);
  54018. if (index !== -1) {
  54019. this.actions.splice(index, 1);
  54020. ActionManager.Triggers[action.trigger] -= 1;
  54021. if (ActionManager.Triggers[action.trigger] === 0) {
  54022. delete ActionManager.Triggers[action.trigger];
  54023. }
  54024. delete action._actionManager;
  54025. return true;
  54026. }
  54027. return false;
  54028. };
  54029. /**
  54030. * Process a specific trigger
  54031. * @param trigger defines the trigger to process
  54032. * @param evt defines the event details to be processed
  54033. */
  54034. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54035. for (var index = 0; index < this.actions.length; index++) {
  54036. var action = this.actions[index];
  54037. if (action.trigger === trigger) {
  54038. if (evt) {
  54039. if (trigger === ActionManager.OnKeyUpTrigger
  54040. || trigger === ActionManager.OnKeyDownTrigger) {
  54041. var parameter = action.getTriggerParameter();
  54042. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54043. if (!parameter.toLowerCase) {
  54044. continue;
  54045. }
  54046. var lowerCase = parameter.toLowerCase();
  54047. if (lowerCase !== evt.sourceEvent.key) {
  54048. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54049. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54050. if (actualkey !== lowerCase) {
  54051. continue;
  54052. }
  54053. }
  54054. }
  54055. }
  54056. }
  54057. action._executeCurrent(evt);
  54058. }
  54059. }
  54060. };
  54061. /** @hidden */
  54062. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54063. var properties = propertyPath.split(".");
  54064. for (var index = 0; index < properties.length - 1; index++) {
  54065. target = target[properties[index]];
  54066. }
  54067. return target;
  54068. };
  54069. /** @hidden */
  54070. ActionManager.prototype._getProperty = function (propertyPath) {
  54071. var properties = propertyPath.split(".");
  54072. return properties[properties.length - 1];
  54073. };
  54074. /**
  54075. * Serialize this manager to a JSON object
  54076. * @param name defines the property name to store this manager
  54077. * @returns a JSON representation of this manager
  54078. */
  54079. ActionManager.prototype.serialize = function (name) {
  54080. var root = {
  54081. children: new Array(),
  54082. name: name,
  54083. type: 3,
  54084. properties: new Array() // Empty for root but required
  54085. };
  54086. for (var i = 0; i < this.actions.length; i++) {
  54087. var triggerObject = {
  54088. type: 0,
  54089. children: new Array(),
  54090. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54091. properties: new Array()
  54092. };
  54093. var triggerOptions = this.actions[i].triggerOptions;
  54094. if (triggerOptions && typeof triggerOptions !== "number") {
  54095. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54096. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54097. }
  54098. else {
  54099. var parameter = {};
  54100. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54101. if (triggerOptions.parameter.mesh) {
  54102. parameter._meshId = triggerOptions.parameter.mesh.id;
  54103. }
  54104. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54105. }
  54106. }
  54107. // Serialize child action, recursively
  54108. this.actions[i].serialize(triggerObject);
  54109. // Add serialized trigger
  54110. root.children.push(triggerObject);
  54111. }
  54112. return root;
  54113. };
  54114. /**
  54115. * Creates a new ActionManager from a JSON data
  54116. * @param parsedActions defines the JSON data to read from
  54117. * @param object defines the hosting mesh
  54118. * @param scene defines the hosting scene
  54119. */
  54120. ActionManager.Parse = function (parsedActions, object, scene) {
  54121. var actionManager = new ActionManager(scene);
  54122. if (object === null)
  54123. scene.actionManager = actionManager;
  54124. else
  54125. object.actionManager = actionManager;
  54126. // instanciate a new object
  54127. var instanciate = function (name, params) {
  54128. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54129. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54130. newInstance.constructor.apply(newInstance, params);
  54131. return newInstance;
  54132. };
  54133. var parseParameter = function (name, value, target, propertyPath) {
  54134. if (propertyPath === null) {
  54135. // String, boolean or float
  54136. var floatValue = parseFloat(value);
  54137. if (value === "true" || value === "false")
  54138. return value === "true";
  54139. else
  54140. return isNaN(floatValue) ? value : floatValue;
  54141. }
  54142. var effectiveTarget = propertyPath.split(".");
  54143. var values = value.split(",");
  54144. // Get effective Target
  54145. for (var i = 0; i < effectiveTarget.length; i++) {
  54146. target = target[effectiveTarget[i]];
  54147. }
  54148. // Return appropriate value with its type
  54149. if (typeof (target) === "boolean")
  54150. return values[0] === "true";
  54151. if (typeof (target) === "string")
  54152. return values[0];
  54153. // Parameters with multiple values such as Vector3 etc.
  54154. var split = new Array();
  54155. for (var i = 0; i < values.length; i++)
  54156. split.push(parseFloat(values[i]));
  54157. if (target instanceof BABYLON.Vector3)
  54158. return BABYLON.Vector3.FromArray(split);
  54159. if (target instanceof BABYLON.Vector4)
  54160. return BABYLON.Vector4.FromArray(split);
  54161. if (target instanceof BABYLON.Color3)
  54162. return BABYLON.Color3.FromArray(split);
  54163. if (target instanceof BABYLON.Color4)
  54164. return BABYLON.Color4.FromArray(split);
  54165. return parseFloat(values[0]);
  54166. };
  54167. // traverse graph per trigger
  54168. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54169. if (combineArray === void 0) { combineArray = null; }
  54170. if (parsedAction.detached)
  54171. return;
  54172. var parameters = new Array();
  54173. var target = null;
  54174. var propertyPath = null;
  54175. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54176. // Parameters
  54177. if (parsedAction.type === 2)
  54178. parameters.push(actionManager);
  54179. else
  54180. parameters.push(trigger);
  54181. if (combine) {
  54182. var actions = new Array();
  54183. for (var j = 0; j < parsedAction.combine.length; j++) {
  54184. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54185. }
  54186. parameters.push(actions);
  54187. }
  54188. else {
  54189. for (var i = 0; i < parsedAction.properties.length; i++) {
  54190. var value = parsedAction.properties[i].value;
  54191. var name = parsedAction.properties[i].name;
  54192. var targetType = parsedAction.properties[i].targetType;
  54193. if (name === "target")
  54194. if (targetType !== null && targetType === "SceneProperties")
  54195. value = target = scene;
  54196. else
  54197. value = target = scene.getNodeByName(value);
  54198. else if (name === "parent")
  54199. value = scene.getNodeByName(value);
  54200. else if (name === "sound")
  54201. value = scene.getSoundByName(value);
  54202. else if (name !== "propertyPath") {
  54203. if (parsedAction.type === 2 && name === "operator")
  54204. value = BABYLON.ValueCondition[value];
  54205. else
  54206. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54207. }
  54208. else {
  54209. propertyPath = value;
  54210. }
  54211. parameters.push(value);
  54212. }
  54213. }
  54214. if (combineArray === null) {
  54215. parameters.push(condition);
  54216. }
  54217. else {
  54218. parameters.push(null);
  54219. }
  54220. // If interpolate value action
  54221. if (parsedAction.name === "InterpolateValueAction") {
  54222. var param = parameters[parameters.length - 2];
  54223. parameters[parameters.length - 1] = param;
  54224. parameters[parameters.length - 2] = condition;
  54225. }
  54226. // Action or condition(s) and not CombineAction
  54227. var newAction = instanciate(parsedAction.name, parameters);
  54228. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54229. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54230. if (action)
  54231. action.then(nothing);
  54232. else
  54233. actionManager.registerAction(nothing);
  54234. action = nothing;
  54235. }
  54236. if (combineArray === null) {
  54237. if (newAction instanceof BABYLON.Condition) {
  54238. condition = newAction;
  54239. newAction = action;
  54240. }
  54241. else {
  54242. condition = null;
  54243. if (action)
  54244. action.then(newAction);
  54245. else
  54246. actionManager.registerAction(newAction);
  54247. }
  54248. }
  54249. else {
  54250. combineArray.push(newAction);
  54251. }
  54252. for (var i = 0; i < parsedAction.children.length; i++)
  54253. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54254. };
  54255. // triggers
  54256. for (var i = 0; i < parsedActions.children.length; i++) {
  54257. var triggerParams;
  54258. var trigger = parsedActions.children[i];
  54259. if (trigger.properties.length > 0) {
  54260. var param = trigger.properties[0].value;
  54261. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54262. if (value._meshId) {
  54263. value.mesh = scene.getMeshByID(value._meshId);
  54264. }
  54265. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54266. }
  54267. else
  54268. triggerParams = ActionManager[trigger.name];
  54269. for (var j = 0; j < trigger.children.length; j++) {
  54270. if (!trigger.detached)
  54271. traverse(trigger.children[j], triggerParams, null, null);
  54272. }
  54273. }
  54274. };
  54275. /**
  54276. * Get a trigger name by index
  54277. * @param trigger defines the trigger index
  54278. * @returns a trigger name
  54279. */
  54280. ActionManager.GetTriggerName = function (trigger) {
  54281. switch (trigger) {
  54282. case 0: return "NothingTrigger";
  54283. case 1: return "OnPickTrigger";
  54284. case 2: return "OnLeftPickTrigger";
  54285. case 3: return "OnRightPickTrigger";
  54286. case 4: return "OnCenterPickTrigger";
  54287. case 5: return "OnPickDownTrigger";
  54288. case 6: return "OnPickUpTrigger";
  54289. case 7: return "OnLongPressTrigger";
  54290. case 8: return "OnPointerOverTrigger";
  54291. case 9: return "OnPointerOutTrigger";
  54292. case 10: return "OnEveryFrameTrigger";
  54293. case 11: return "OnIntersectionEnterTrigger";
  54294. case 12: return "OnIntersectionExitTrigger";
  54295. case 13: return "OnKeyDownTrigger";
  54296. case 14: return "OnKeyUpTrigger";
  54297. case 15: return "OnPickOutTrigger";
  54298. default: return "";
  54299. }
  54300. };
  54301. // Statics
  54302. ActionManager._NothingTrigger = 0;
  54303. ActionManager._OnPickTrigger = 1;
  54304. ActionManager._OnLeftPickTrigger = 2;
  54305. ActionManager._OnRightPickTrigger = 3;
  54306. ActionManager._OnCenterPickTrigger = 4;
  54307. ActionManager._OnPickDownTrigger = 5;
  54308. ActionManager._OnDoublePickTrigger = 6;
  54309. ActionManager._OnPickUpTrigger = 7;
  54310. ActionManager._OnLongPressTrigger = 8;
  54311. ActionManager._OnPointerOverTrigger = 9;
  54312. ActionManager._OnPointerOutTrigger = 10;
  54313. ActionManager._OnEveryFrameTrigger = 11;
  54314. ActionManager._OnIntersectionEnterTrigger = 12;
  54315. ActionManager._OnIntersectionExitTrigger = 13;
  54316. ActionManager._OnKeyDownTrigger = 14;
  54317. ActionManager._OnKeyUpTrigger = 15;
  54318. ActionManager._OnPickOutTrigger = 16;
  54319. /** Gets the list of active triggers */
  54320. ActionManager.Triggers = {};
  54321. return ActionManager;
  54322. }());
  54323. BABYLON.ActionManager = ActionManager;
  54324. })(BABYLON || (BABYLON = {}));
  54325. //# sourceMappingURL=babylon.actionManager.js.map
  54326. var BABYLON;
  54327. (function (BABYLON) {
  54328. var InterpolateValueAction = /** @class */ (function (_super) {
  54329. __extends(InterpolateValueAction, _super);
  54330. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54331. if (duration === void 0) { duration = 1000; }
  54332. var _this = _super.call(this, triggerOptions, condition) || this;
  54333. _this.propertyPath = propertyPath;
  54334. _this.value = value;
  54335. _this.duration = duration;
  54336. _this.stopOtherAnimations = stopOtherAnimations;
  54337. _this.onInterpolationDone = onInterpolationDone;
  54338. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54339. _this._target = _this._effectiveTarget = target;
  54340. return _this;
  54341. }
  54342. InterpolateValueAction.prototype._prepare = function () {
  54343. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54344. this._property = this._getProperty(this.propertyPath);
  54345. };
  54346. InterpolateValueAction.prototype.execute = function () {
  54347. var _this = this;
  54348. var scene = this._actionManager.getScene();
  54349. var keys = [
  54350. {
  54351. frame: 0,
  54352. value: this._effectiveTarget[this._property]
  54353. }, {
  54354. frame: 100,
  54355. value: this.value
  54356. }
  54357. ];
  54358. var dataType;
  54359. if (typeof this.value === "number") {
  54360. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54361. }
  54362. else if (this.value instanceof BABYLON.Color3) {
  54363. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54364. }
  54365. else if (this.value instanceof BABYLON.Vector3) {
  54366. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54367. }
  54368. else if (this.value instanceof BABYLON.Matrix) {
  54369. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54370. }
  54371. else if (this.value instanceof BABYLON.Quaternion) {
  54372. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54373. }
  54374. else {
  54375. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54376. return;
  54377. }
  54378. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54379. animation.setKeys(keys);
  54380. if (this.stopOtherAnimations) {
  54381. scene.stopAnimation(this._effectiveTarget);
  54382. }
  54383. var wrapper = function () {
  54384. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54385. if (_this.onInterpolationDone) {
  54386. _this.onInterpolationDone();
  54387. }
  54388. };
  54389. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54390. };
  54391. InterpolateValueAction.prototype.serialize = function (parent) {
  54392. return _super.prototype._serialize.call(this, {
  54393. name: "InterpolateValueAction",
  54394. properties: [
  54395. BABYLON.Action._GetTargetProperty(this._target),
  54396. { name: "propertyPath", value: this.propertyPath },
  54397. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54398. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54399. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54400. ]
  54401. }, parent);
  54402. };
  54403. return InterpolateValueAction;
  54404. }(BABYLON.Action));
  54405. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54406. })(BABYLON || (BABYLON = {}));
  54407. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54408. var BABYLON;
  54409. (function (BABYLON) {
  54410. var SwitchBooleanAction = /** @class */ (function (_super) {
  54411. __extends(SwitchBooleanAction, _super);
  54412. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54413. var _this = _super.call(this, triggerOptions, condition) || this;
  54414. _this.propertyPath = propertyPath;
  54415. _this._target = _this._effectiveTarget = target;
  54416. return _this;
  54417. }
  54418. SwitchBooleanAction.prototype._prepare = function () {
  54419. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54420. this._property = this._getProperty(this.propertyPath);
  54421. };
  54422. SwitchBooleanAction.prototype.execute = function () {
  54423. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54424. };
  54425. SwitchBooleanAction.prototype.serialize = function (parent) {
  54426. return _super.prototype._serialize.call(this, {
  54427. name: "SwitchBooleanAction",
  54428. properties: [
  54429. BABYLON.Action._GetTargetProperty(this._target),
  54430. { name: "propertyPath", value: this.propertyPath }
  54431. ]
  54432. }, parent);
  54433. };
  54434. return SwitchBooleanAction;
  54435. }(BABYLON.Action));
  54436. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54437. var SetStateAction = /** @class */ (function (_super) {
  54438. __extends(SetStateAction, _super);
  54439. function SetStateAction(triggerOptions, target, value, condition) {
  54440. var _this = _super.call(this, triggerOptions, condition) || this;
  54441. _this.value = value;
  54442. _this._target = target;
  54443. return _this;
  54444. }
  54445. SetStateAction.prototype.execute = function () {
  54446. this._target.state = this.value;
  54447. };
  54448. SetStateAction.prototype.serialize = function (parent) {
  54449. return _super.prototype._serialize.call(this, {
  54450. name: "SetStateAction",
  54451. properties: [
  54452. BABYLON.Action._GetTargetProperty(this._target),
  54453. { name: "value", value: this.value }
  54454. ]
  54455. }, parent);
  54456. };
  54457. return SetStateAction;
  54458. }(BABYLON.Action));
  54459. BABYLON.SetStateAction = SetStateAction;
  54460. var SetValueAction = /** @class */ (function (_super) {
  54461. __extends(SetValueAction, _super);
  54462. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54463. var _this = _super.call(this, triggerOptions, condition) || this;
  54464. _this.propertyPath = propertyPath;
  54465. _this.value = value;
  54466. _this._target = _this._effectiveTarget = target;
  54467. return _this;
  54468. }
  54469. SetValueAction.prototype._prepare = function () {
  54470. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54471. this._property = this._getProperty(this.propertyPath);
  54472. };
  54473. SetValueAction.prototype.execute = function () {
  54474. this._effectiveTarget[this._property] = this.value;
  54475. if (this._target.markAsDirty) {
  54476. this._target.markAsDirty(this._property);
  54477. }
  54478. };
  54479. SetValueAction.prototype.serialize = function (parent) {
  54480. return _super.prototype._serialize.call(this, {
  54481. name: "SetValueAction",
  54482. properties: [
  54483. BABYLON.Action._GetTargetProperty(this._target),
  54484. { name: "propertyPath", value: this.propertyPath },
  54485. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54486. ]
  54487. }, parent);
  54488. };
  54489. return SetValueAction;
  54490. }(BABYLON.Action));
  54491. BABYLON.SetValueAction = SetValueAction;
  54492. var IncrementValueAction = /** @class */ (function (_super) {
  54493. __extends(IncrementValueAction, _super);
  54494. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54495. var _this = _super.call(this, triggerOptions, condition) || this;
  54496. _this.propertyPath = propertyPath;
  54497. _this.value = value;
  54498. _this._target = _this._effectiveTarget = target;
  54499. return _this;
  54500. }
  54501. IncrementValueAction.prototype._prepare = function () {
  54502. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54503. this._property = this._getProperty(this.propertyPath);
  54504. if (typeof this._effectiveTarget[this._property] !== "number") {
  54505. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54506. }
  54507. };
  54508. IncrementValueAction.prototype.execute = function () {
  54509. this._effectiveTarget[this._property] += this.value;
  54510. if (this._target.markAsDirty) {
  54511. this._target.markAsDirty(this._property);
  54512. }
  54513. };
  54514. IncrementValueAction.prototype.serialize = function (parent) {
  54515. return _super.prototype._serialize.call(this, {
  54516. name: "IncrementValueAction",
  54517. properties: [
  54518. BABYLON.Action._GetTargetProperty(this._target),
  54519. { name: "propertyPath", value: this.propertyPath },
  54520. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54521. ]
  54522. }, parent);
  54523. };
  54524. return IncrementValueAction;
  54525. }(BABYLON.Action));
  54526. BABYLON.IncrementValueAction = IncrementValueAction;
  54527. var PlayAnimationAction = /** @class */ (function (_super) {
  54528. __extends(PlayAnimationAction, _super);
  54529. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54530. var _this = _super.call(this, triggerOptions, condition) || this;
  54531. _this.from = from;
  54532. _this.to = to;
  54533. _this.loop = loop;
  54534. _this._target = target;
  54535. return _this;
  54536. }
  54537. PlayAnimationAction.prototype._prepare = function () {
  54538. };
  54539. PlayAnimationAction.prototype.execute = function () {
  54540. var scene = this._actionManager.getScene();
  54541. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54542. };
  54543. PlayAnimationAction.prototype.serialize = function (parent) {
  54544. return _super.prototype._serialize.call(this, {
  54545. name: "PlayAnimationAction",
  54546. properties: [
  54547. BABYLON.Action._GetTargetProperty(this._target),
  54548. { name: "from", value: String(this.from) },
  54549. { name: "to", value: String(this.to) },
  54550. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54551. ]
  54552. }, parent);
  54553. };
  54554. return PlayAnimationAction;
  54555. }(BABYLON.Action));
  54556. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54557. var StopAnimationAction = /** @class */ (function (_super) {
  54558. __extends(StopAnimationAction, _super);
  54559. function StopAnimationAction(triggerOptions, target, condition) {
  54560. var _this = _super.call(this, triggerOptions, condition) || this;
  54561. _this._target = target;
  54562. return _this;
  54563. }
  54564. StopAnimationAction.prototype._prepare = function () {
  54565. };
  54566. StopAnimationAction.prototype.execute = function () {
  54567. var scene = this._actionManager.getScene();
  54568. scene.stopAnimation(this._target);
  54569. };
  54570. StopAnimationAction.prototype.serialize = function (parent) {
  54571. return _super.prototype._serialize.call(this, {
  54572. name: "StopAnimationAction",
  54573. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54574. }, parent);
  54575. };
  54576. return StopAnimationAction;
  54577. }(BABYLON.Action));
  54578. BABYLON.StopAnimationAction = StopAnimationAction;
  54579. var DoNothingAction = /** @class */ (function (_super) {
  54580. __extends(DoNothingAction, _super);
  54581. function DoNothingAction(triggerOptions, condition) {
  54582. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54583. return _super.call(this, triggerOptions, condition) || this;
  54584. }
  54585. DoNothingAction.prototype.execute = function () {
  54586. };
  54587. DoNothingAction.prototype.serialize = function (parent) {
  54588. return _super.prototype._serialize.call(this, {
  54589. name: "DoNothingAction",
  54590. properties: []
  54591. }, parent);
  54592. };
  54593. return DoNothingAction;
  54594. }(BABYLON.Action));
  54595. BABYLON.DoNothingAction = DoNothingAction;
  54596. var CombineAction = /** @class */ (function (_super) {
  54597. __extends(CombineAction, _super);
  54598. function CombineAction(triggerOptions, children, condition) {
  54599. var _this = _super.call(this, triggerOptions, condition) || this;
  54600. _this.children = children;
  54601. return _this;
  54602. }
  54603. CombineAction.prototype._prepare = function () {
  54604. for (var index = 0; index < this.children.length; index++) {
  54605. this.children[index]._actionManager = this._actionManager;
  54606. this.children[index]._prepare();
  54607. }
  54608. };
  54609. CombineAction.prototype.execute = function (evt) {
  54610. for (var index = 0; index < this.children.length; index++) {
  54611. this.children[index].execute(evt);
  54612. }
  54613. };
  54614. CombineAction.prototype.serialize = function (parent) {
  54615. var serializationObject = _super.prototype._serialize.call(this, {
  54616. name: "CombineAction",
  54617. properties: [],
  54618. combine: []
  54619. }, parent);
  54620. for (var i = 0; i < this.children.length; i++) {
  54621. serializationObject.combine.push(this.children[i].serialize(null));
  54622. }
  54623. return serializationObject;
  54624. };
  54625. return CombineAction;
  54626. }(BABYLON.Action));
  54627. BABYLON.CombineAction = CombineAction;
  54628. var ExecuteCodeAction = /** @class */ (function (_super) {
  54629. __extends(ExecuteCodeAction, _super);
  54630. function ExecuteCodeAction(triggerOptions, func, condition) {
  54631. var _this = _super.call(this, triggerOptions, condition) || this;
  54632. _this.func = func;
  54633. return _this;
  54634. }
  54635. ExecuteCodeAction.prototype.execute = function (evt) {
  54636. this.func(evt);
  54637. };
  54638. return ExecuteCodeAction;
  54639. }(BABYLON.Action));
  54640. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54641. var SetParentAction = /** @class */ (function (_super) {
  54642. __extends(SetParentAction, _super);
  54643. function SetParentAction(triggerOptions, target, parent, condition) {
  54644. var _this = _super.call(this, triggerOptions, condition) || this;
  54645. _this._target = target;
  54646. _this._parent = parent;
  54647. return _this;
  54648. }
  54649. SetParentAction.prototype._prepare = function () {
  54650. };
  54651. SetParentAction.prototype.execute = function () {
  54652. if (this._target.parent === this._parent) {
  54653. return;
  54654. }
  54655. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54656. invertParentWorldMatrix.invert();
  54657. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54658. this._target.parent = this._parent;
  54659. };
  54660. SetParentAction.prototype.serialize = function (parent) {
  54661. return _super.prototype._serialize.call(this, {
  54662. name: "SetParentAction",
  54663. properties: [
  54664. BABYLON.Action._GetTargetProperty(this._target),
  54665. BABYLON.Action._GetTargetProperty(this._parent),
  54666. ]
  54667. }, parent);
  54668. };
  54669. return SetParentAction;
  54670. }(BABYLON.Action));
  54671. BABYLON.SetParentAction = SetParentAction;
  54672. var PlaySoundAction = /** @class */ (function (_super) {
  54673. __extends(PlaySoundAction, _super);
  54674. function PlaySoundAction(triggerOptions, sound, condition) {
  54675. var _this = _super.call(this, triggerOptions, condition) || this;
  54676. _this._sound = sound;
  54677. return _this;
  54678. }
  54679. PlaySoundAction.prototype._prepare = function () {
  54680. };
  54681. PlaySoundAction.prototype.execute = function () {
  54682. if (this._sound !== undefined)
  54683. this._sound.play();
  54684. };
  54685. PlaySoundAction.prototype.serialize = function (parent) {
  54686. return _super.prototype._serialize.call(this, {
  54687. name: "PlaySoundAction",
  54688. properties: [{ name: "sound", value: this._sound.name }]
  54689. }, parent);
  54690. };
  54691. return PlaySoundAction;
  54692. }(BABYLON.Action));
  54693. BABYLON.PlaySoundAction = PlaySoundAction;
  54694. var StopSoundAction = /** @class */ (function (_super) {
  54695. __extends(StopSoundAction, _super);
  54696. function StopSoundAction(triggerOptions, sound, condition) {
  54697. var _this = _super.call(this, triggerOptions, condition) || this;
  54698. _this._sound = sound;
  54699. return _this;
  54700. }
  54701. StopSoundAction.prototype._prepare = function () {
  54702. };
  54703. StopSoundAction.prototype.execute = function () {
  54704. if (this._sound !== undefined)
  54705. this._sound.stop();
  54706. };
  54707. StopSoundAction.prototype.serialize = function (parent) {
  54708. return _super.prototype._serialize.call(this, {
  54709. name: "StopSoundAction",
  54710. properties: [{ name: "sound", value: this._sound.name }]
  54711. }, parent);
  54712. };
  54713. return StopSoundAction;
  54714. }(BABYLON.Action));
  54715. BABYLON.StopSoundAction = StopSoundAction;
  54716. })(BABYLON || (BABYLON = {}));
  54717. //# sourceMappingURL=babylon.directActions.js.map
  54718. var BABYLON;
  54719. (function (BABYLON) {
  54720. var SpriteManager = /** @class */ (function () {
  54721. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54722. if (epsilon === void 0) { epsilon = 0.01; }
  54723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54724. this.name = name;
  54725. this.sprites = new Array();
  54726. this.renderingGroupId = 0;
  54727. this.layerMask = 0x0FFFFFFF;
  54728. this.fogEnabled = true;
  54729. this.isPickable = false;
  54730. /**
  54731. * An event triggered when the manager is disposed.
  54732. */
  54733. this.onDisposeObservable = new BABYLON.Observable();
  54734. this._vertexBuffers = {};
  54735. this._capacity = capacity;
  54736. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54737. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54738. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54739. if (cellSize.width && cellSize.height) {
  54740. this.cellWidth = cellSize.width;
  54741. this.cellHeight = cellSize.height;
  54742. }
  54743. else if (cellSize !== undefined) {
  54744. this.cellWidth = cellSize;
  54745. this.cellHeight = cellSize;
  54746. }
  54747. else {
  54748. return;
  54749. }
  54750. this._epsilon = epsilon;
  54751. this._scene = scene;
  54752. this._scene.spriteManagers.push(this);
  54753. var indices = [];
  54754. var index = 0;
  54755. for (var count = 0; count < capacity; count++) {
  54756. indices.push(index);
  54757. indices.push(index + 1);
  54758. indices.push(index + 2);
  54759. indices.push(index);
  54760. indices.push(index + 2);
  54761. indices.push(index + 3);
  54762. index += 4;
  54763. }
  54764. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54765. // VBO
  54766. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54767. this._vertexData = new Float32Array(capacity * 16 * 4);
  54768. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54769. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54770. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54771. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54772. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54773. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54774. this._vertexBuffers["options"] = options;
  54775. this._vertexBuffers["cellInfo"] = cellInfo;
  54776. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54777. // Effects
  54778. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54779. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54780. }
  54781. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54782. set: function (callback) {
  54783. if (this._onDisposeObserver) {
  54784. this.onDisposeObservable.remove(this._onDisposeObserver);
  54785. }
  54786. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54787. },
  54788. enumerable: true,
  54789. configurable: true
  54790. });
  54791. Object.defineProperty(SpriteManager.prototype, "texture", {
  54792. get: function () {
  54793. return this._spriteTexture;
  54794. },
  54795. set: function (value) {
  54796. this._spriteTexture = value;
  54797. },
  54798. enumerable: true,
  54799. configurable: true
  54800. });
  54801. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54802. var arrayOffset = index * 16;
  54803. if (offsetX === 0)
  54804. offsetX = this._epsilon;
  54805. else if (offsetX === 1)
  54806. offsetX = 1 - this._epsilon;
  54807. if (offsetY === 0)
  54808. offsetY = this._epsilon;
  54809. else if (offsetY === 1)
  54810. offsetY = 1 - this._epsilon;
  54811. this._vertexData[arrayOffset] = sprite.position.x;
  54812. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54813. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54814. this._vertexData[arrayOffset + 3] = sprite.angle;
  54815. this._vertexData[arrayOffset + 4] = sprite.width;
  54816. this._vertexData[arrayOffset + 5] = sprite.height;
  54817. this._vertexData[arrayOffset + 6] = offsetX;
  54818. this._vertexData[arrayOffset + 7] = offsetY;
  54819. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54820. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54821. var offset = (sprite.cellIndex / rowSize) >> 0;
  54822. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54823. this._vertexData[arrayOffset + 11] = offset;
  54824. // Color
  54825. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54826. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54827. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54828. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54829. };
  54830. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54831. var count = Math.min(this._capacity, this.sprites.length);
  54832. var min = BABYLON.Vector3.Zero();
  54833. var max = BABYLON.Vector3.Zero();
  54834. var distance = Number.MAX_VALUE;
  54835. var currentSprite = null;
  54836. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54837. var cameraView = camera.getViewMatrix();
  54838. for (var index = 0; index < count; index++) {
  54839. var sprite = this.sprites[index];
  54840. if (!sprite) {
  54841. continue;
  54842. }
  54843. if (predicate) {
  54844. if (!predicate(sprite)) {
  54845. continue;
  54846. }
  54847. }
  54848. else if (!sprite.isPickable) {
  54849. continue;
  54850. }
  54851. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54852. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54853. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54854. if (ray.intersectsBoxMinMax(min, max)) {
  54855. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54856. if (distance > currentDistance) {
  54857. distance = currentDistance;
  54858. currentSprite = sprite;
  54859. if (fastCheck) {
  54860. break;
  54861. }
  54862. }
  54863. }
  54864. }
  54865. if (currentSprite) {
  54866. var result = new BABYLON.PickingInfo();
  54867. result.hit = true;
  54868. result.pickedSprite = currentSprite;
  54869. result.distance = distance;
  54870. return result;
  54871. }
  54872. return null;
  54873. };
  54874. SpriteManager.prototype.render = function () {
  54875. // Check
  54876. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54877. return;
  54878. var engine = this._scene.getEngine();
  54879. var baseSize = this._spriteTexture.getBaseSize();
  54880. // Sprites
  54881. var deltaTime = engine.getDeltaTime();
  54882. var max = Math.min(this._capacity, this.sprites.length);
  54883. var rowSize = baseSize.width / this.cellWidth;
  54884. var offset = 0;
  54885. for (var index = 0; index < max; index++) {
  54886. var sprite = this.sprites[index];
  54887. if (!sprite) {
  54888. continue;
  54889. }
  54890. sprite._animate(deltaTime);
  54891. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54892. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54893. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54894. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54895. }
  54896. this._buffer.update(this._vertexData);
  54897. // Render
  54898. var effect = this._effectBase;
  54899. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54900. effect = this._effectFog;
  54901. }
  54902. engine.enableEffect(effect);
  54903. var viewMatrix = this._scene.getViewMatrix();
  54904. effect.setTexture("diffuseSampler", this._spriteTexture);
  54905. effect.setMatrix("view", viewMatrix);
  54906. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54907. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54908. // Fog
  54909. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54910. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54911. effect.setColor3("vFogColor", this._scene.fogColor);
  54912. }
  54913. // VBOs
  54914. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54915. // Draw order
  54916. engine.setDepthFunctionToLessOrEqual();
  54917. effect.setBool("alphaTest", true);
  54918. engine.setColorWrite(false);
  54919. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54920. engine.setColorWrite(true);
  54921. effect.setBool("alphaTest", false);
  54922. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54925. };
  54926. SpriteManager.prototype.dispose = function () {
  54927. if (this._buffer) {
  54928. this._buffer.dispose();
  54929. this._buffer = null;
  54930. }
  54931. if (this._indexBuffer) {
  54932. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54933. this._indexBuffer = null;
  54934. }
  54935. if (this._spriteTexture) {
  54936. this._spriteTexture.dispose();
  54937. this._spriteTexture = null;
  54938. }
  54939. // Remove from scene
  54940. var index = this._scene.spriteManagers.indexOf(this);
  54941. this._scene.spriteManagers.splice(index, 1);
  54942. // Callback
  54943. this.onDisposeObservable.notifyObservers(this);
  54944. this.onDisposeObservable.clear();
  54945. };
  54946. return SpriteManager;
  54947. }());
  54948. BABYLON.SpriteManager = SpriteManager;
  54949. })(BABYLON || (BABYLON = {}));
  54950. //# sourceMappingURL=babylon.spriteManager.js.map
  54951. var BABYLON;
  54952. (function (BABYLON) {
  54953. var Sprite = /** @class */ (function () {
  54954. function Sprite(name, manager) {
  54955. this.name = name;
  54956. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54957. this.width = 1.0;
  54958. this.height = 1.0;
  54959. this.angle = 0;
  54960. this.cellIndex = 0;
  54961. this.invertU = 0;
  54962. this.invertV = 0;
  54963. this.animations = new Array();
  54964. this.isPickable = false;
  54965. this._animationStarted = false;
  54966. this._loopAnimation = false;
  54967. this._fromIndex = 0;
  54968. this._toIndex = 0;
  54969. this._delay = 0;
  54970. this._direction = 1;
  54971. this._time = 0;
  54972. this._manager = manager;
  54973. this._manager.sprites.push(this);
  54974. this.position = BABYLON.Vector3.Zero();
  54975. }
  54976. Object.defineProperty(Sprite.prototype, "size", {
  54977. get: function () {
  54978. return this.width;
  54979. },
  54980. set: function (value) {
  54981. this.width = value;
  54982. this.height = value;
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54988. this._fromIndex = from;
  54989. this._toIndex = to;
  54990. this._loopAnimation = loop;
  54991. this._delay = delay;
  54992. this._animationStarted = true;
  54993. this._direction = from < to ? 1 : -1;
  54994. this.cellIndex = from;
  54995. this._time = 0;
  54996. this._onAnimationEnd = onAnimationEnd;
  54997. };
  54998. Sprite.prototype.stopAnimation = function () {
  54999. this._animationStarted = false;
  55000. };
  55001. Sprite.prototype._animate = function (deltaTime) {
  55002. if (!this._animationStarted)
  55003. return;
  55004. this._time += deltaTime;
  55005. if (this._time > this._delay) {
  55006. this._time = this._time % this._delay;
  55007. this.cellIndex += this._direction;
  55008. if (this.cellIndex > this._toIndex) {
  55009. if (this._loopAnimation) {
  55010. this.cellIndex = this._fromIndex;
  55011. }
  55012. else {
  55013. this.cellIndex = this._toIndex;
  55014. this._animationStarted = false;
  55015. if (this._onAnimationEnd) {
  55016. this._onAnimationEnd();
  55017. }
  55018. if (this.disposeWhenFinishedAnimating) {
  55019. this.dispose();
  55020. }
  55021. }
  55022. }
  55023. }
  55024. };
  55025. Sprite.prototype.dispose = function () {
  55026. for (var i = 0; i < this._manager.sprites.length; i++) {
  55027. if (this._manager.sprites[i] == this) {
  55028. this._manager.sprites.splice(i, 1);
  55029. }
  55030. }
  55031. };
  55032. return Sprite;
  55033. }());
  55034. BABYLON.Sprite = Sprite;
  55035. })(BABYLON || (BABYLON = {}));
  55036. //# sourceMappingURL=babylon.sprite.js.map
  55037. var BABYLON;
  55038. (function (BABYLON) {
  55039. var IntersectionInfo = /** @class */ (function () {
  55040. function IntersectionInfo(bu, bv, distance) {
  55041. this.bu = bu;
  55042. this.bv = bv;
  55043. this.distance = distance;
  55044. this.faceId = 0;
  55045. this.subMeshId = 0;
  55046. }
  55047. return IntersectionInfo;
  55048. }());
  55049. BABYLON.IntersectionInfo = IntersectionInfo;
  55050. /**
  55051. * Information about the result of picking within a scene
  55052. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55053. */
  55054. var PickingInfo = /** @class */ (function () {
  55055. function PickingInfo() {
  55056. /**
  55057. * If the pick collided with an object
  55058. */
  55059. this.hit = false;
  55060. /**
  55061. * Distance away where the pick collided
  55062. */
  55063. this.distance = 0;
  55064. /**
  55065. * The location of pick collision
  55066. */
  55067. this.pickedPoint = null;
  55068. /**
  55069. * The mesh corrisponding the the pick collision
  55070. */
  55071. this.pickedMesh = null;
  55072. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55073. this.bu = 0;
  55074. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55075. this.bv = 0;
  55076. /** The id of the face on the mesh that was picked */
  55077. this.faceId = -1;
  55078. /** Id of the the submesh that was picked */
  55079. this.subMeshId = 0;
  55080. /** If a sprite was picked, this will be the sprite the pick collided with */
  55081. this.pickedSprite = null;
  55082. /**
  55083. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55084. */
  55085. this.originMesh = null;
  55086. /**
  55087. * The ray that was used to perform the picking.
  55088. */
  55089. this.ray = null;
  55090. }
  55091. /**
  55092. * Gets the normal corrispodning to the face the pick collided with
  55093. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55094. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55095. * @returns The normal corrispodning to the face the pick collided with
  55096. */
  55097. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55098. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55099. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55100. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55101. return null;
  55102. }
  55103. var indices = this.pickedMesh.getIndices();
  55104. if (!indices) {
  55105. return null;
  55106. }
  55107. var result;
  55108. if (useVerticesNormals) {
  55109. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55110. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55111. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55112. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55113. normal0 = normal0.scale(this.bu);
  55114. normal1 = normal1.scale(this.bv);
  55115. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55116. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55117. }
  55118. else {
  55119. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55120. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55121. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55122. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55123. var p1p2 = vertex1.subtract(vertex2);
  55124. var p3p2 = vertex3.subtract(vertex2);
  55125. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55126. }
  55127. if (useWorldCoordinates) {
  55128. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55129. }
  55130. return BABYLON.Vector3.Normalize(result);
  55131. };
  55132. /**
  55133. * Gets the texture coordinates of where the pick occured
  55134. * @returns the vector containing the coordnates of the texture
  55135. */
  55136. PickingInfo.prototype.getTextureCoordinates = function () {
  55137. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55138. return null;
  55139. }
  55140. var indices = this.pickedMesh.getIndices();
  55141. if (!indices) {
  55142. return null;
  55143. }
  55144. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55145. if (!uvs) {
  55146. return null;
  55147. }
  55148. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55149. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55150. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55151. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55152. uv1 = uv1.scale(this.bu);
  55153. uv2 = uv2.scale(this.bv);
  55154. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55155. };
  55156. return PickingInfo;
  55157. }());
  55158. BABYLON.PickingInfo = PickingInfo;
  55159. })(BABYLON || (BABYLON = {}));
  55160. //# sourceMappingURL=babylon.pickingInfo.js.map
  55161. var BABYLON;
  55162. (function (BABYLON) {
  55163. var Ray = /** @class */ (function () {
  55164. function Ray(origin, direction, length) {
  55165. if (length === void 0) { length = Number.MAX_VALUE; }
  55166. this.origin = origin;
  55167. this.direction = direction;
  55168. this.length = length;
  55169. }
  55170. // Methods
  55171. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55172. var d = 0.0;
  55173. var maxValue = Number.MAX_VALUE;
  55174. var inv;
  55175. var min;
  55176. var max;
  55177. var temp;
  55178. if (Math.abs(this.direction.x) < 0.0000001) {
  55179. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55180. return false;
  55181. }
  55182. }
  55183. else {
  55184. inv = 1.0 / this.direction.x;
  55185. min = (minimum.x - this.origin.x) * inv;
  55186. max = (maximum.x - this.origin.x) * inv;
  55187. if (max === -Infinity) {
  55188. max = Infinity;
  55189. }
  55190. if (min > max) {
  55191. temp = min;
  55192. min = max;
  55193. max = temp;
  55194. }
  55195. d = Math.max(min, d);
  55196. maxValue = Math.min(max, maxValue);
  55197. if (d > maxValue) {
  55198. return false;
  55199. }
  55200. }
  55201. if (Math.abs(this.direction.y) < 0.0000001) {
  55202. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55203. return false;
  55204. }
  55205. }
  55206. else {
  55207. inv = 1.0 / this.direction.y;
  55208. min = (minimum.y - this.origin.y) * inv;
  55209. max = (maximum.y - this.origin.y) * inv;
  55210. if (max === -Infinity) {
  55211. max = Infinity;
  55212. }
  55213. if (min > max) {
  55214. temp = min;
  55215. min = max;
  55216. max = temp;
  55217. }
  55218. d = Math.max(min, d);
  55219. maxValue = Math.min(max, maxValue);
  55220. if (d > maxValue) {
  55221. return false;
  55222. }
  55223. }
  55224. if (Math.abs(this.direction.z) < 0.0000001) {
  55225. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55226. return false;
  55227. }
  55228. }
  55229. else {
  55230. inv = 1.0 / this.direction.z;
  55231. min = (minimum.z - this.origin.z) * inv;
  55232. max = (maximum.z - this.origin.z) * inv;
  55233. if (max === -Infinity) {
  55234. max = Infinity;
  55235. }
  55236. if (min > max) {
  55237. temp = min;
  55238. min = max;
  55239. max = temp;
  55240. }
  55241. d = Math.max(min, d);
  55242. maxValue = Math.min(max, maxValue);
  55243. if (d > maxValue) {
  55244. return false;
  55245. }
  55246. }
  55247. return true;
  55248. };
  55249. Ray.prototype.intersectsBox = function (box) {
  55250. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55251. };
  55252. Ray.prototype.intersectsSphere = function (sphere) {
  55253. var x = sphere.center.x - this.origin.x;
  55254. var y = sphere.center.y - this.origin.y;
  55255. var z = sphere.center.z - this.origin.z;
  55256. var pyth = (x * x) + (y * y) + (z * z);
  55257. var rr = sphere.radius * sphere.radius;
  55258. if (pyth <= rr) {
  55259. return true;
  55260. }
  55261. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55262. if (dot < 0.0) {
  55263. return false;
  55264. }
  55265. var temp = pyth - (dot * dot);
  55266. return temp <= rr;
  55267. };
  55268. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55269. if (!this._edge1) {
  55270. this._edge1 = BABYLON.Vector3.Zero();
  55271. this._edge2 = BABYLON.Vector3.Zero();
  55272. this._pvec = BABYLON.Vector3.Zero();
  55273. this._tvec = BABYLON.Vector3.Zero();
  55274. this._qvec = BABYLON.Vector3.Zero();
  55275. }
  55276. vertex1.subtractToRef(vertex0, this._edge1);
  55277. vertex2.subtractToRef(vertex0, this._edge2);
  55278. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55279. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55280. if (det === 0) {
  55281. return null;
  55282. }
  55283. var invdet = 1 / det;
  55284. this.origin.subtractToRef(vertex0, this._tvec);
  55285. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55286. if (bu < 0 || bu > 1.0) {
  55287. return null;
  55288. }
  55289. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55290. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55291. if (bv < 0 || bu + bv > 1.0) {
  55292. return null;
  55293. }
  55294. //check if the distance is longer than the predefined length.
  55295. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55296. if (distance > this.length) {
  55297. return null;
  55298. }
  55299. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55300. };
  55301. Ray.prototype.intersectsPlane = function (plane) {
  55302. var distance;
  55303. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55304. if (Math.abs(result1) < 9.99999997475243E-07) {
  55305. return null;
  55306. }
  55307. else {
  55308. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55309. distance = (-plane.d - result2) / result1;
  55310. if (distance < 0.0) {
  55311. if (distance < -9.99999997475243E-07) {
  55312. return null;
  55313. }
  55314. else {
  55315. return 0;
  55316. }
  55317. }
  55318. return distance;
  55319. }
  55320. };
  55321. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55322. var tm = BABYLON.Tmp.Matrix[0];
  55323. mesh.getWorldMatrix().invertToRef(tm);
  55324. if (this._tmpRay) {
  55325. Ray.TransformToRef(this, tm, this._tmpRay);
  55326. }
  55327. else {
  55328. this._tmpRay = Ray.Transform(this, tm);
  55329. }
  55330. return mesh.intersects(this._tmpRay, fastCheck);
  55331. };
  55332. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55333. if (results) {
  55334. results.length = 0;
  55335. }
  55336. else {
  55337. results = [];
  55338. }
  55339. for (var i = 0; i < meshes.length; i++) {
  55340. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55341. if (pickInfo.hit) {
  55342. results.push(pickInfo);
  55343. }
  55344. }
  55345. results.sort(this._comparePickingInfo);
  55346. return results;
  55347. };
  55348. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55349. if (pickingInfoA.distance < pickingInfoB.distance) {
  55350. return -1;
  55351. }
  55352. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55353. return 1;
  55354. }
  55355. else {
  55356. return 0;
  55357. }
  55358. };
  55359. /**
  55360. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55361. * @param sega the first point of the segment to test the intersection against
  55362. * @param segb the second point of the segment to test the intersection against
  55363. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55364. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55365. */
  55366. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55367. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55368. var u = segb.subtract(sega);
  55369. var v = rsegb.subtract(this.origin);
  55370. var w = sega.subtract(this.origin);
  55371. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55372. var b = BABYLON.Vector3.Dot(u, v);
  55373. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55374. var d = BABYLON.Vector3.Dot(u, w);
  55375. var e = BABYLON.Vector3.Dot(v, w);
  55376. var D = a * c - b * b; // always >= 0
  55377. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55378. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55379. // compute the line parameters of the two closest points
  55380. if (D < Ray.smallnum) { // the lines are almost parallel
  55381. sN = 0.0; // force using point P0 on segment S1
  55382. sD = 1.0; // to prevent possible division by 0.0 later
  55383. tN = e;
  55384. tD = c;
  55385. }
  55386. else { // get the closest points on the infinite lines
  55387. sN = (b * e - c * d);
  55388. tN = (a * e - b * d);
  55389. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55390. sN = 0.0;
  55391. tN = e;
  55392. tD = c;
  55393. }
  55394. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55395. sN = sD;
  55396. tN = e + b;
  55397. tD = c;
  55398. }
  55399. }
  55400. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55401. tN = 0.0;
  55402. // recompute sc for this edge
  55403. if (-d < 0.0) {
  55404. sN = 0.0;
  55405. }
  55406. else if (-d > a)
  55407. sN = sD;
  55408. else {
  55409. sN = -d;
  55410. sD = a;
  55411. }
  55412. }
  55413. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55414. tN = tD;
  55415. // recompute sc for this edge
  55416. if ((-d + b) < 0.0) {
  55417. sN = 0;
  55418. }
  55419. else if ((-d + b) > a) {
  55420. sN = sD;
  55421. }
  55422. else {
  55423. sN = (-d + b);
  55424. sD = a;
  55425. }
  55426. }
  55427. // finally do the division to get sc and tc
  55428. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55429. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55430. // get the difference of the two closest points
  55431. var qtc = v.multiplyByFloats(tc, tc, tc);
  55432. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55433. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55434. if (isIntersected) {
  55435. return qtc.length();
  55436. }
  55437. return -1;
  55438. };
  55439. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55440. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55441. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55442. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55443. this.direction.normalize();
  55444. return this;
  55445. };
  55446. // Statics
  55447. Ray.Zero = function () {
  55448. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55449. };
  55450. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55451. var result = Ray.Zero();
  55452. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55453. };
  55454. /**
  55455. * 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
  55456. * transformed to the given world matrix.
  55457. * @param origin The origin point
  55458. * @param end The end point
  55459. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55460. */
  55461. Ray.CreateNewFromTo = function (origin, end, world) {
  55462. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55463. var direction = end.subtract(origin);
  55464. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55465. direction.normalize();
  55466. return Ray.Transform(new Ray(origin, direction, length), world);
  55467. };
  55468. Ray.Transform = function (ray, matrix) {
  55469. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55470. Ray.TransformToRef(ray, matrix, result);
  55471. return result;
  55472. };
  55473. Ray.TransformToRef = function (ray, matrix, result) {
  55474. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55475. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55476. result.length = ray.length;
  55477. var dir = result.direction;
  55478. var len = dir.length();
  55479. if (!(len === 0 || len === 1)) {
  55480. var num = 1.0 / len;
  55481. dir.x *= num;
  55482. dir.y *= num;
  55483. dir.z *= num;
  55484. result.length *= len;
  55485. }
  55486. };
  55487. Ray.smallnum = 0.00000001;
  55488. Ray.rayl = 10e8;
  55489. return Ray;
  55490. }());
  55491. BABYLON.Ray = Ray;
  55492. })(BABYLON || (BABYLON = {}));
  55493. //# sourceMappingURL=babylon.ray.js.map
  55494. var BABYLON;
  55495. (function (BABYLON) {
  55496. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55497. if (boxMin.x > sphereCenter.x + sphereRadius)
  55498. return false;
  55499. if (sphereCenter.x - sphereRadius > boxMax.x)
  55500. return false;
  55501. if (boxMin.y > sphereCenter.y + sphereRadius)
  55502. return false;
  55503. if (sphereCenter.y - sphereRadius > boxMax.y)
  55504. return false;
  55505. if (boxMin.z > sphereCenter.z + sphereRadius)
  55506. return false;
  55507. if (sphereCenter.z - sphereRadius > boxMax.z)
  55508. return false;
  55509. return true;
  55510. };
  55511. var getLowestRoot = (function () {
  55512. var result = { root: 0, found: false };
  55513. return function (a, b, c, maxR) {
  55514. result.root = 0;
  55515. result.found = false;
  55516. var determinant = b * b - 4.0 * a * c;
  55517. if (determinant < 0)
  55518. return result;
  55519. var sqrtD = Math.sqrt(determinant);
  55520. var r1 = (-b - sqrtD) / (2.0 * a);
  55521. var r2 = (-b + sqrtD) / (2.0 * a);
  55522. if (r1 > r2) {
  55523. var temp = r2;
  55524. r2 = r1;
  55525. r1 = temp;
  55526. }
  55527. if (r1 > 0 && r1 < maxR) {
  55528. result.root = r1;
  55529. result.found = true;
  55530. return result;
  55531. }
  55532. if (r2 > 0 && r2 < maxR) {
  55533. result.root = r2;
  55534. result.found = true;
  55535. return result;
  55536. }
  55537. return result;
  55538. };
  55539. })();
  55540. var Collider = /** @class */ (function () {
  55541. function Collider() {
  55542. this._collisionPoint = BABYLON.Vector3.Zero();
  55543. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55544. this._tempVector = BABYLON.Vector3.Zero();
  55545. this._tempVector2 = BABYLON.Vector3.Zero();
  55546. this._tempVector3 = BABYLON.Vector3.Zero();
  55547. this._tempVector4 = BABYLON.Vector3.Zero();
  55548. this._edge = BABYLON.Vector3.Zero();
  55549. this._baseToVertex = BABYLON.Vector3.Zero();
  55550. this._destinationPoint = BABYLON.Vector3.Zero();
  55551. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55552. this._displacementVector = BABYLON.Vector3.Zero();
  55553. this._radius = BABYLON.Vector3.One();
  55554. this._retry = 0;
  55555. this._basePointWorld = BABYLON.Vector3.Zero();
  55556. this._velocityWorld = BABYLON.Vector3.Zero();
  55557. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55558. this._collisionMask = -1;
  55559. }
  55560. Object.defineProperty(Collider.prototype, "collisionMask", {
  55561. get: function () {
  55562. return this._collisionMask;
  55563. },
  55564. set: function (mask) {
  55565. this._collisionMask = !isNaN(mask) ? mask : -1;
  55566. },
  55567. enumerable: true,
  55568. configurable: true
  55569. });
  55570. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55571. /**
  55572. * Gets the plane normal used to compute the sliding response (in local space)
  55573. */
  55574. get: function () {
  55575. return this._slidePlaneNormal;
  55576. },
  55577. enumerable: true,
  55578. configurable: true
  55579. });
  55580. // Methods
  55581. Collider.prototype._initialize = function (source, dir, e) {
  55582. this._velocity = dir;
  55583. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55584. this._basePoint = source;
  55585. source.multiplyToRef(this._radius, this._basePointWorld);
  55586. dir.multiplyToRef(this._radius, this._velocityWorld);
  55587. this._velocityWorldLength = this._velocityWorld.length();
  55588. this._epsilon = e;
  55589. this.collisionFound = false;
  55590. };
  55591. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55592. pa.subtractToRef(point, this._tempVector);
  55593. pb.subtractToRef(point, this._tempVector2);
  55594. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55595. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55596. if (d < 0)
  55597. return false;
  55598. pc.subtractToRef(point, this._tempVector3);
  55599. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55600. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55601. if (d < 0)
  55602. return false;
  55603. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55604. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55605. return d >= 0;
  55606. };
  55607. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55608. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55609. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55610. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55611. return false;
  55612. }
  55613. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55614. return false;
  55615. return true;
  55616. };
  55617. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55618. var t0;
  55619. var embeddedInPlane = false;
  55620. //defensive programming, actually not needed.
  55621. if (!trianglePlaneArray) {
  55622. trianglePlaneArray = [];
  55623. }
  55624. if (!trianglePlaneArray[faceIndex]) {
  55625. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55626. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55627. }
  55628. var trianglePlane = trianglePlaneArray[faceIndex];
  55629. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55630. return;
  55631. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55632. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55633. if (normalDotVelocity == 0) {
  55634. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55635. return;
  55636. embeddedInPlane = true;
  55637. t0 = 0;
  55638. }
  55639. else {
  55640. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55641. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55642. if (t0 > t1) {
  55643. var temp = t1;
  55644. t1 = t0;
  55645. t0 = temp;
  55646. }
  55647. if (t0 > 1.0 || t1 < 0.0)
  55648. return;
  55649. if (t0 < 0)
  55650. t0 = 0;
  55651. if (t0 > 1.0)
  55652. t0 = 1.0;
  55653. }
  55654. this._collisionPoint.copyFromFloats(0, 0, 0);
  55655. var found = false;
  55656. var t = 1.0;
  55657. if (!embeddedInPlane) {
  55658. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55659. this._velocity.scaleToRef(t0, this._tempVector);
  55660. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55661. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55662. found = true;
  55663. t = t0;
  55664. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55665. }
  55666. }
  55667. if (!found) {
  55668. var velocitySquaredLength = this._velocity.lengthSquared();
  55669. var a = velocitySquaredLength;
  55670. this._basePoint.subtractToRef(p1, this._tempVector);
  55671. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55672. var c = this._tempVector.lengthSquared() - 1.0;
  55673. var lowestRoot = getLowestRoot(a, b, c, t);
  55674. if (lowestRoot.found) {
  55675. t = lowestRoot.root;
  55676. found = true;
  55677. this._collisionPoint.copyFrom(p1);
  55678. }
  55679. this._basePoint.subtractToRef(p2, this._tempVector);
  55680. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55681. c = this._tempVector.lengthSquared() - 1.0;
  55682. lowestRoot = getLowestRoot(a, b, c, t);
  55683. if (lowestRoot.found) {
  55684. t = lowestRoot.root;
  55685. found = true;
  55686. this._collisionPoint.copyFrom(p2);
  55687. }
  55688. this._basePoint.subtractToRef(p3, this._tempVector);
  55689. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55690. c = this._tempVector.lengthSquared() - 1.0;
  55691. lowestRoot = getLowestRoot(a, b, c, t);
  55692. if (lowestRoot.found) {
  55693. t = lowestRoot.root;
  55694. found = true;
  55695. this._collisionPoint.copyFrom(p3);
  55696. }
  55697. p2.subtractToRef(p1, this._edge);
  55698. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55699. var edgeSquaredLength = this._edge.lengthSquared();
  55700. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55701. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55702. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55703. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55704. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55705. lowestRoot = getLowestRoot(a, b, c, t);
  55706. if (lowestRoot.found) {
  55707. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55708. if (f >= 0.0 && f <= 1.0) {
  55709. t = lowestRoot.root;
  55710. found = true;
  55711. this._edge.scaleInPlace(f);
  55712. p1.addToRef(this._edge, this._collisionPoint);
  55713. }
  55714. }
  55715. p3.subtractToRef(p2, this._edge);
  55716. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55717. edgeSquaredLength = this._edge.lengthSquared();
  55718. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55719. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55723. lowestRoot = getLowestRoot(a, b, c, t);
  55724. if (lowestRoot.found) {
  55725. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55726. if (f >= 0.0 && f <= 1.0) {
  55727. t = lowestRoot.root;
  55728. found = true;
  55729. this._edge.scaleInPlace(f);
  55730. p2.addToRef(this._edge, this._collisionPoint);
  55731. }
  55732. }
  55733. p1.subtractToRef(p3, this._edge);
  55734. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55735. edgeSquaredLength = this._edge.lengthSquared();
  55736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55741. lowestRoot = getLowestRoot(a, b, c, t);
  55742. if (lowestRoot.found) {
  55743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55744. if (f >= 0.0 && f <= 1.0) {
  55745. t = lowestRoot.root;
  55746. found = true;
  55747. this._edge.scaleInPlace(f);
  55748. p3.addToRef(this._edge, this._collisionPoint);
  55749. }
  55750. }
  55751. }
  55752. if (found) {
  55753. var distToCollision = t * this._velocity.length();
  55754. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55755. if (!this.intersectionPoint) {
  55756. this.intersectionPoint = this._collisionPoint.clone();
  55757. }
  55758. else {
  55759. this.intersectionPoint.copyFrom(this._collisionPoint);
  55760. }
  55761. this._nearestDistance = distToCollision;
  55762. this.collisionFound = true;
  55763. }
  55764. }
  55765. };
  55766. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55767. for (var i = indexStart; i < indexEnd; i += 3) {
  55768. var p1 = pts[indices[i] - decal];
  55769. var p2 = pts[indices[i + 1] - decal];
  55770. var p3 = pts[indices[i + 2] - decal];
  55771. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55772. }
  55773. };
  55774. Collider.prototype._getResponse = function (pos, vel) {
  55775. pos.addToRef(vel, this._destinationPoint);
  55776. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55777. this._basePoint.addToRef(vel, pos);
  55778. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55779. this._slidePlaneNormal.normalize();
  55780. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55781. pos.addInPlace(this._displacementVector);
  55782. this.intersectionPoint.addInPlace(this._displacementVector);
  55783. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55784. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55785. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55786. };
  55787. return Collider;
  55788. }());
  55789. BABYLON.Collider = Collider;
  55790. })(BABYLON || (BABYLON = {}));
  55791. //# sourceMappingURL=babylon.collider.js.map
  55792. var BABYLON;
  55793. (function (BABYLON) {
  55794. //WebWorker code will be inserted to this variable.
  55795. BABYLON.CollisionWorker = "";
  55796. /** Defines supported task for worker process */
  55797. var WorkerTaskType;
  55798. (function (WorkerTaskType) {
  55799. /** Initialization */
  55800. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55801. /** Update of geometry */
  55802. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55803. /** Evaluate collision */
  55804. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55805. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55806. /** Defines kind of replies returned by worker */
  55807. var WorkerReplyType;
  55808. (function (WorkerReplyType) {
  55809. /** Success */
  55810. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55811. /** Unkown error */
  55812. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55813. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55814. var CollisionCoordinatorWorker = /** @class */ (function () {
  55815. function CollisionCoordinatorWorker() {
  55816. var _this = this;
  55817. this._scaledPosition = BABYLON.Vector3.Zero();
  55818. this._scaledVelocity = BABYLON.Vector3.Zero();
  55819. this.onMeshUpdated = function (transformNode) {
  55820. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55821. };
  55822. this.onGeometryUpdated = function (geometry) {
  55823. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55824. };
  55825. this._afterRender = function () {
  55826. if (!_this._init)
  55827. return;
  55828. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55829. return;
  55830. }
  55831. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55832. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55833. if (_this._runningUpdated > 4) {
  55834. return;
  55835. }
  55836. ++_this._runningUpdated;
  55837. var payload = {
  55838. updatedMeshes: _this._addUpdateMeshesList,
  55839. updatedGeometries: _this._addUpdateGeometriesList,
  55840. removedGeometries: _this._toRemoveGeometryArray,
  55841. removedMeshes: _this._toRemoveMeshesArray
  55842. };
  55843. var message = {
  55844. payload: payload,
  55845. taskType: WorkerTaskType.UPDATE
  55846. };
  55847. var serializable = [];
  55848. for (var id in payload.updatedGeometries) {
  55849. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55850. //prepare transferables
  55851. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55852. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55853. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55854. }
  55855. }
  55856. _this._worker.postMessage(message, serializable);
  55857. _this._addUpdateMeshesList = {};
  55858. _this._addUpdateGeometriesList = {};
  55859. _this._toRemoveGeometryArray = [];
  55860. _this._toRemoveMeshesArray = [];
  55861. };
  55862. this._onMessageFromWorker = function (e) {
  55863. var returnData = e.data;
  55864. if (returnData.error != WorkerReplyType.SUCCESS) {
  55865. //TODO what errors can be returned from the worker?
  55866. BABYLON.Tools.Warn("error returned from worker!");
  55867. return;
  55868. }
  55869. switch (returnData.taskType) {
  55870. case WorkerTaskType.INIT:
  55871. _this._init = true;
  55872. //Update the worked with ALL of the scene's current state
  55873. _this._scene.meshes.forEach(function (mesh) {
  55874. _this.onMeshAdded(mesh);
  55875. });
  55876. _this._scene.getGeometries().forEach(function (geometry) {
  55877. _this.onGeometryAdded(geometry);
  55878. });
  55879. break;
  55880. case WorkerTaskType.UPDATE:
  55881. _this._runningUpdated--;
  55882. break;
  55883. case WorkerTaskType.COLLIDE:
  55884. var returnPayload = returnData.payload;
  55885. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55886. return;
  55887. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55888. if (callback) {
  55889. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55890. if (mesh) {
  55891. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55892. }
  55893. }
  55894. //cleanup
  55895. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55896. break;
  55897. }
  55898. };
  55899. this._collisionsCallbackArray = [];
  55900. this._init = false;
  55901. this._runningUpdated = 0;
  55902. this._addUpdateMeshesList = {};
  55903. this._addUpdateGeometriesList = {};
  55904. this._toRemoveGeometryArray = [];
  55905. this._toRemoveMeshesArray = [];
  55906. }
  55907. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55908. if (!this._init)
  55909. return;
  55910. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55911. return;
  55912. position.divideToRef(collider._radius, this._scaledPosition);
  55913. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55914. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55915. var payload = {
  55916. collider: {
  55917. position: this._scaledPosition.asArray(),
  55918. velocity: this._scaledVelocity.asArray(),
  55919. radius: collider._radius.asArray()
  55920. },
  55921. collisionId: collisionIndex,
  55922. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55923. maximumRetry: maximumRetry
  55924. };
  55925. var message = {
  55926. payload: payload,
  55927. taskType: WorkerTaskType.COLLIDE
  55928. };
  55929. this._worker.postMessage(message);
  55930. };
  55931. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55932. this._scene = scene;
  55933. this._scene.registerAfterRender(this._afterRender);
  55934. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55935. this._worker = new Worker(workerUrl);
  55936. this._worker.onmessage = this._onMessageFromWorker;
  55937. var message = {
  55938. payload: {},
  55939. taskType: WorkerTaskType.INIT
  55940. };
  55941. this._worker.postMessage(message);
  55942. };
  55943. CollisionCoordinatorWorker.prototype.destroy = function () {
  55944. this._scene.unregisterAfterRender(this._afterRender);
  55945. this._worker.terminate();
  55946. };
  55947. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55948. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55949. this.onMeshUpdated(mesh);
  55950. };
  55951. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55952. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55953. };
  55954. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55955. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55956. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55957. this.onGeometryUpdated(geometry);
  55958. };
  55959. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55960. this._toRemoveGeometryArray.push(geometry.id);
  55961. };
  55962. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55963. var submeshes = [];
  55964. if (mesh.subMeshes) {
  55965. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55966. var boundingInfo = sm.getBoundingInfo();
  55967. return {
  55968. position: idx,
  55969. verticesStart: sm.verticesStart,
  55970. verticesCount: sm.verticesCount,
  55971. indexStart: sm.indexStart,
  55972. indexCount: sm.indexCount,
  55973. hasMaterial: !!sm.getMaterial(),
  55974. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55975. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55976. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55977. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55978. };
  55979. });
  55980. }
  55981. var geometryId = null;
  55982. if (mesh instanceof BABYLON.Mesh) {
  55983. var geometry = mesh.geometry;
  55984. geometryId = geometry ? geometry.id : null;
  55985. }
  55986. else if (mesh instanceof BABYLON.InstancedMesh) {
  55987. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55988. geometryId = geometry ? geometry.id : null;
  55989. }
  55990. var boundingInfo = mesh.getBoundingInfo();
  55991. return {
  55992. uniqueId: mesh.uniqueId,
  55993. id: mesh.id,
  55994. name: mesh.name,
  55995. geometryId: geometryId,
  55996. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55997. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55998. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55999. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56000. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56001. subMeshes: submeshes,
  56002. checkCollisions: mesh.checkCollisions
  56003. };
  56004. };
  56005. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56006. return {
  56007. id: geometry.id,
  56008. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56009. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56010. indices: new Uint32Array(geometry.getIndices() || []),
  56011. };
  56012. };
  56013. return CollisionCoordinatorWorker;
  56014. }());
  56015. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56016. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56017. function CollisionCoordinatorLegacy() {
  56018. this._scaledPosition = BABYLON.Vector3.Zero();
  56019. this._scaledVelocity = BABYLON.Vector3.Zero();
  56020. this._finalPosition = BABYLON.Vector3.Zero();
  56021. }
  56022. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56023. position.divideToRef(collider._radius, this._scaledPosition);
  56024. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56025. collider.collidedMesh = null;
  56026. collider._retry = 0;
  56027. collider._initialVelocity = this._scaledVelocity;
  56028. collider._initialPosition = this._scaledPosition;
  56029. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56030. this._finalPosition.multiplyInPlace(collider._radius);
  56031. //run the callback
  56032. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56033. };
  56034. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56035. this._scene = scene;
  56036. };
  56037. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56038. //Legacy need no destruction method.
  56039. };
  56040. //No update in legacy mode
  56041. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56042. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56043. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56044. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56045. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56046. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56047. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56048. if (excludedMesh === void 0) { excludedMesh = null; }
  56049. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56050. if (collider._retry >= maximumRetry) {
  56051. finalPosition.copyFrom(position);
  56052. return;
  56053. }
  56054. // Check if this is a mesh else camera or -1
  56055. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56056. collider._initialize(position, velocity, closeDistance);
  56057. // Check all meshes
  56058. for (var index = 0; index < this._scene.meshes.length; index++) {
  56059. var mesh = this._scene.meshes[index];
  56060. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56061. mesh._checkCollision(collider);
  56062. }
  56063. }
  56064. if (!collider.collisionFound) {
  56065. position.addToRef(velocity, finalPosition);
  56066. return;
  56067. }
  56068. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56069. collider._getResponse(position, velocity);
  56070. }
  56071. if (velocity.length() <= closeDistance) {
  56072. finalPosition.copyFrom(position);
  56073. return;
  56074. }
  56075. collider._retry++;
  56076. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56077. };
  56078. return CollisionCoordinatorLegacy;
  56079. }());
  56080. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56081. })(BABYLON || (BABYLON = {}));
  56082. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56083. var BABYLON;
  56084. (function (BABYLON) {
  56085. /**
  56086. * A particle represents one of the element emitted by a particle system.
  56087. * This is mainly define by its coordinates, direction, velocity and age.
  56088. */
  56089. var Particle = /** @class */ (function () {
  56090. /**
  56091. * Creates a new instance Particle
  56092. * @param particleSystem the particle system the particle belongs to
  56093. */
  56094. function Particle(
  56095. /**
  56096. * particleSystem the particle system the particle belongs to.
  56097. */
  56098. particleSystem) {
  56099. this.particleSystem = particleSystem;
  56100. /**
  56101. * The world position of the particle in the scene.
  56102. */
  56103. this.position = BABYLON.Vector3.Zero();
  56104. /**
  56105. * The world direction of the particle in the scene.
  56106. */
  56107. this.direction = BABYLON.Vector3.Zero();
  56108. /**
  56109. * The color of the particle.
  56110. */
  56111. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56112. /**
  56113. * The color change of the particle per step.
  56114. */
  56115. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56116. /**
  56117. * Defines how long will the life of the particle be.
  56118. */
  56119. this.lifeTime = 1.0;
  56120. /**
  56121. * The current age of the particle.
  56122. */
  56123. this.age = 0;
  56124. /**
  56125. * The current size of the particle.
  56126. */
  56127. this.size = 0;
  56128. /**
  56129. * The current scale of the particle.
  56130. */
  56131. this.scale = new BABYLON.Vector2(1, 1);
  56132. /**
  56133. * The current angle of the particle.
  56134. */
  56135. this.angle = 0;
  56136. /**
  56137. * Defines how fast is the angle changing.
  56138. */
  56139. this.angularSpeed = 0;
  56140. /**
  56141. * Defines the cell index used by the particle to be rendered from a sprite.
  56142. */
  56143. this.cellIndex = 0;
  56144. this._currentFrameCounter = 0;
  56145. if (!this.particleSystem.isAnimationSheetEnabled) {
  56146. return;
  56147. }
  56148. this.updateCellInfoFromSystem();
  56149. }
  56150. Particle.prototype.updateCellInfoFromSystem = function () {
  56151. this.cellIndex = this.particleSystem.startSpriteCellID;
  56152. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56153. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56154. }
  56155. else {
  56156. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56157. }
  56158. };
  56159. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56160. // (ageOffset / scaledUpdateSpeed) / available cells
  56161. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56162. this._currentFrameCounter += scaledUpdateSpeed;
  56163. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56164. this._currentFrameCounter = 0;
  56165. this.cellIndex++;
  56166. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56167. this.cellIndex = this.particleSystem.endSpriteCellID;
  56168. }
  56169. }
  56170. };
  56171. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56172. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56173. this.cellIndex++;
  56174. this._currentFrameCounter = 0;
  56175. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56176. if (this.particleSystem.spriteCellLoop) {
  56177. this.cellIndex = this.particleSystem.startSpriteCellID;
  56178. }
  56179. else {
  56180. this.cellIndex = this.particleSystem.endSpriteCellID;
  56181. }
  56182. }
  56183. }
  56184. else {
  56185. this._currentFrameCounter++;
  56186. }
  56187. };
  56188. /**
  56189. * Copy the properties of particle to another one.
  56190. * @param other the particle to copy the information to.
  56191. */
  56192. Particle.prototype.copyTo = function (other) {
  56193. other.position.copyFrom(this.position);
  56194. other.direction.copyFrom(this.direction);
  56195. other.color.copyFrom(this.color);
  56196. other.colorStep.copyFrom(this.colorStep);
  56197. other.lifeTime = this.lifeTime;
  56198. other.age = this.age;
  56199. other.size = this.size;
  56200. other.scale.copyFrom(this.scale);
  56201. other.angle = this.angle;
  56202. other.angularSpeed = this.angularSpeed;
  56203. other.particleSystem = this.particleSystem;
  56204. other.cellIndex = this.cellIndex;
  56205. };
  56206. return Particle;
  56207. }());
  56208. BABYLON.Particle = Particle;
  56209. })(BABYLON || (BABYLON = {}));
  56210. //# sourceMappingURL=babylon.particle.js.map
  56211. var BABYLON;
  56212. (function (BABYLON) {
  56213. /**
  56214. * This represents a particle system in Babylon.
  56215. * 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.
  56216. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56217. * @example https://doc.babylonjs.com/babylon101/particles
  56218. */
  56219. var ParticleSystem = /** @class */ (function () {
  56220. /**
  56221. * Instantiates a particle system.
  56222. * 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.
  56223. * @param name The name of the particle system
  56224. * @param capacity The max number of particles alive at the same time
  56225. * @param scene The scene the particle system belongs to
  56226. * @param customEffect a custom effect used to change the way particles are rendered by default
  56227. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56228. * @param epsilon Offset used to render the particles
  56229. */
  56230. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56231. if (customEffect === void 0) { customEffect = null; }
  56232. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56233. if (epsilon === void 0) { epsilon = 0.01; }
  56234. var _this = this;
  56235. /**
  56236. * List of animations used by the particle system.
  56237. */
  56238. this.animations = [];
  56239. /**
  56240. * The rendering group used by the Particle system to chose when to render.
  56241. */
  56242. this.renderingGroupId = 0;
  56243. /**
  56244. * The emitter represents the Mesh or position we are attaching the particle system to.
  56245. */
  56246. this.emitter = null;
  56247. /**
  56248. * The maximum number of particles to emit per frame
  56249. */
  56250. this.emitRate = 10;
  56251. /**
  56252. * If you want to launch only a few particles at once, that can be done, as well.
  56253. */
  56254. this.manualEmitCount = -1;
  56255. /**
  56256. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56257. */
  56258. this.updateSpeed = 0.01;
  56259. /**
  56260. * The amount of time the particle system is running (depends of the overall update speed).
  56261. */
  56262. this.targetStopDuration = 0;
  56263. /**
  56264. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56265. */
  56266. this.disposeOnStop = false;
  56267. /**
  56268. * Minimum power of emitting particles.
  56269. */
  56270. this.minEmitPower = 1;
  56271. /**
  56272. * Maximum power of emitting particles.
  56273. */
  56274. this.maxEmitPower = 1;
  56275. /**
  56276. * Minimum life time of emitting particles.
  56277. */
  56278. this.minLifeTime = 1;
  56279. /**
  56280. * Maximum life time of emitting particles.
  56281. */
  56282. this.maxLifeTime = 1;
  56283. /**
  56284. * Minimum Size of emitting particles.
  56285. */
  56286. this.minSize = 1;
  56287. /**
  56288. * Maximum Size of emitting particles.
  56289. */
  56290. this.maxSize = 1;
  56291. /**
  56292. * Minimum scale of emitting particles on X axis.
  56293. */
  56294. this.minScaleX = 1;
  56295. /**
  56296. * Maximum scale of emitting particles on X axis.
  56297. */
  56298. this.maxScaleX = 1;
  56299. /**
  56300. * Minimum scale of emitting particles on Y axis.
  56301. */
  56302. this.minScaleY = 1;
  56303. /**
  56304. * Maximum scale of emitting particles on Y axis.
  56305. */
  56306. this.maxScaleY = 1;
  56307. /**
  56308. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56309. */
  56310. this.minAngularSpeed = 0;
  56311. /**
  56312. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56313. */
  56314. this.maxAngularSpeed = 0;
  56315. /**
  56316. * The layer mask we are rendering the particles through.
  56317. */
  56318. this.layerMask = 0x0FFFFFFF;
  56319. /**
  56320. * This can help using your own shader to render the particle system.
  56321. * The according effect will be created
  56322. */
  56323. this.customShader = null;
  56324. /**
  56325. * By default particle system starts as soon as they are created. This prevents the
  56326. * automatic start to happen and let you decide when to start emitting particles.
  56327. */
  56328. this.preventAutoStart = false;
  56329. /**
  56330. * Callback triggered when the particle animation is ending.
  56331. */
  56332. this.onAnimationEnd = null;
  56333. /**
  56334. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56335. */
  56336. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56337. /**
  56338. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56339. * to override the particles.
  56340. */
  56341. this.forceDepthWrite = false;
  56342. /**
  56343. * You can use gravity if you want to give an orientation to your particles.
  56344. */
  56345. this.gravity = BABYLON.Vector3.Zero();
  56346. /**
  56347. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56348. */
  56349. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56350. /**
  56351. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56352. */
  56353. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56354. /**
  56355. * Color the particle will have at the end of its lifetime.
  56356. */
  56357. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56358. /**
  56359. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56360. */
  56361. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56362. /**
  56363. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56364. */
  56365. this.spriteCellLoop = true;
  56366. /**
  56367. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56368. */
  56369. this.spriteCellChangeSpeed = 0;
  56370. /**
  56371. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56372. */
  56373. this.startSpriteCellID = 0;
  56374. /**
  56375. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56376. */
  56377. this.endSpriteCellID = 0;
  56378. /**
  56379. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56380. */
  56381. this.spriteCellWidth = 0;
  56382. /**
  56383. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56384. */
  56385. this.spriteCellHeight = 0;
  56386. /**
  56387. * An event triggered when the system is disposed.
  56388. */
  56389. this.onDisposeObservable = new BABYLON.Observable();
  56390. this._particles = new Array();
  56391. this._stockParticles = new Array();
  56392. this._newPartsExcess = 0;
  56393. this._vertexBuffers = {};
  56394. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56395. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56396. this._scaledDirection = BABYLON.Vector3.Zero();
  56397. this._scaledGravity = BABYLON.Vector3.Zero();
  56398. this._currentRenderId = -1;
  56399. this._started = false;
  56400. this._stopped = false;
  56401. this._actualFrame = 0;
  56402. this._vertexBufferSize = 12;
  56403. // start of sub system methods
  56404. /**
  56405. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56406. * Its lifetime will start back at 0.
  56407. */
  56408. this.recycleParticle = function (particle) {
  56409. var lastParticle = _this._particles.pop();
  56410. if (lastParticle !== particle) {
  56411. lastParticle.copyTo(particle);
  56412. }
  56413. _this._stockParticles.push(lastParticle);
  56414. };
  56415. this._createParticle = function () {
  56416. var particle;
  56417. if (_this._stockParticles.length !== 0) {
  56418. particle = _this._stockParticles.pop();
  56419. particle.age = 0;
  56420. particle.cellIndex = _this.startSpriteCellID;
  56421. }
  56422. else {
  56423. particle = new BABYLON.Particle(_this);
  56424. }
  56425. return particle;
  56426. };
  56427. this._emitFromParticle = function (particle) {
  56428. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56429. return;
  56430. }
  56431. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56432. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56433. subSystem._rootParticleSystem = _this;
  56434. _this.activeSubSystems.push(subSystem);
  56435. subSystem.start();
  56436. };
  56437. this._appendParticleVertexes = null;
  56438. this.id = name;
  56439. this.name = name;
  56440. this._capacity = capacity;
  56441. this._epsilon = epsilon;
  56442. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56443. if (isAnimationSheetEnabled) {
  56444. this._vertexBufferSize = 13;
  56445. }
  56446. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56447. this._customEffect = customEffect;
  56448. scene.particleSystems.push(this);
  56449. this._createIndexBuffer();
  56450. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  56451. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56452. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56453. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56454. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56455. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  56456. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  56457. if (this._isAnimationSheetEnabled) {
  56458. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  56459. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56460. }
  56461. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56462. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56463. this._vertexBuffers["options"] = options;
  56464. this._vertexBuffers["size"] = size;
  56465. // Default emitter type
  56466. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56467. this.updateFunction = function (particles) {
  56468. for (var index = 0; index < particles.length; index++) {
  56469. var particle = particles[index];
  56470. particle.age += _this._scaledUpdateSpeed;
  56471. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56472. _this._emitFromParticle(particle);
  56473. _this.recycleParticle(particle);
  56474. index--;
  56475. continue;
  56476. }
  56477. else {
  56478. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56479. particle.color.addInPlace(_this._scaledColorStep);
  56480. if (particle.color.a < 0)
  56481. particle.color.a = 0;
  56482. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56483. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56484. particle.position.addInPlace(_this._scaledDirection);
  56485. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56486. particle.direction.addInPlace(_this._scaledGravity);
  56487. if (_this._isAnimationSheetEnabled) {
  56488. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56489. }
  56490. }
  56491. }
  56492. };
  56493. }
  56494. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56495. /**
  56496. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56497. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56498. */
  56499. get: function () {
  56500. if (this.particleEmitterType.direction1) {
  56501. return this.particleEmitterType.direction1;
  56502. }
  56503. return BABYLON.Vector3.Zero();
  56504. },
  56505. set: function (value) {
  56506. if (this.particleEmitterType.direction1) {
  56507. this.particleEmitterType.direction1 = value;
  56508. }
  56509. },
  56510. enumerable: true,
  56511. configurable: true
  56512. });
  56513. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56514. /**
  56515. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56516. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56517. */
  56518. get: function () {
  56519. if (this.particleEmitterType.direction2) {
  56520. return this.particleEmitterType.direction2;
  56521. }
  56522. return BABYLON.Vector3.Zero();
  56523. },
  56524. set: function (value) {
  56525. if (this.particleEmitterType.direction2) {
  56526. this.particleEmitterType.direction2 = value;
  56527. }
  56528. },
  56529. enumerable: true,
  56530. configurable: true
  56531. });
  56532. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56533. /**
  56534. * 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.
  56535. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56536. */
  56537. get: function () {
  56538. if (this.particleEmitterType.minEmitBox) {
  56539. return this.particleEmitterType.minEmitBox;
  56540. }
  56541. return BABYLON.Vector3.Zero();
  56542. },
  56543. set: function (value) {
  56544. if (this.particleEmitterType.minEmitBox) {
  56545. this.particleEmitterType.minEmitBox = value;
  56546. }
  56547. },
  56548. enumerable: true,
  56549. configurable: true
  56550. });
  56551. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56552. /**
  56553. * 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.
  56554. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56555. */
  56556. get: function () {
  56557. if (this.particleEmitterType.maxEmitBox) {
  56558. return this.particleEmitterType.maxEmitBox;
  56559. }
  56560. return BABYLON.Vector3.Zero();
  56561. },
  56562. set: function (value) {
  56563. if (this.particleEmitterType.maxEmitBox) {
  56564. this.particleEmitterType.maxEmitBox = value;
  56565. }
  56566. },
  56567. enumerable: true,
  56568. configurable: true
  56569. });
  56570. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56571. /**
  56572. * Sets a callback that will be triggered when the system is disposed.
  56573. */
  56574. set: function (callback) {
  56575. if (this._onDisposeObserver) {
  56576. this.onDisposeObservable.remove(this._onDisposeObserver);
  56577. }
  56578. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56579. },
  56580. enumerable: true,
  56581. configurable: true
  56582. });
  56583. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56584. /**
  56585. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56586. */
  56587. get: function () {
  56588. return this._isAnimationSheetEnabled;
  56589. },
  56590. enumerable: true,
  56591. configurable: true
  56592. });
  56593. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56594. //end of Sub-emitter
  56595. /**
  56596. * Gets the current list of active particles
  56597. */
  56598. get: function () {
  56599. return this._particles;
  56600. },
  56601. enumerable: true,
  56602. configurable: true
  56603. });
  56604. /**
  56605. * Returns the string "ParticleSystem"
  56606. * @returns a string containing the class name
  56607. */
  56608. ParticleSystem.prototype.getClassName = function () {
  56609. return "ParticleSystem";
  56610. };
  56611. ParticleSystem.prototype._createIndexBuffer = function () {
  56612. var indices = [];
  56613. var index = 0;
  56614. for (var count = 0; count < this._capacity; count++) {
  56615. indices.push(index);
  56616. indices.push(index + 1);
  56617. indices.push(index + 2);
  56618. indices.push(index);
  56619. indices.push(index + 2);
  56620. indices.push(index + 3);
  56621. index += 4;
  56622. }
  56623. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56624. };
  56625. /**
  56626. * Gets the maximum number of particles active at the same time.
  56627. * @returns The max number of active particles.
  56628. */
  56629. ParticleSystem.prototype.getCapacity = function () {
  56630. return this._capacity;
  56631. };
  56632. /**
  56633. * Gets Wether there are still active particles in the system.
  56634. * @returns True if it is alive, otherwise false.
  56635. */
  56636. ParticleSystem.prototype.isAlive = function () {
  56637. return this._alive;
  56638. };
  56639. /**
  56640. * Gets Wether the system has been started.
  56641. * @returns True if it has been started, otherwise false.
  56642. */
  56643. ParticleSystem.prototype.isStarted = function () {
  56644. return this._started;
  56645. };
  56646. /**
  56647. * Starts the particle system and begins to emit.
  56648. */
  56649. ParticleSystem.prototype.start = function () {
  56650. this._started = true;
  56651. this._stopped = false;
  56652. this._actualFrame = 0;
  56653. if (this.subEmitters && this.subEmitters.length != 0) {
  56654. this.activeSubSystems = new Array();
  56655. }
  56656. };
  56657. /**
  56658. * Stops the particle system.
  56659. * @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.
  56660. */
  56661. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56662. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56663. this._stopped = true;
  56664. if (stopSubEmitters) {
  56665. this._stopSubEmitters();
  56666. }
  56667. };
  56668. // animation sheet
  56669. /**
  56670. * Remove all active particles
  56671. */
  56672. ParticleSystem.prototype.reset = function () {
  56673. this._stockParticles = [];
  56674. this._particles = [];
  56675. };
  56676. /**
  56677. * @hidden (for internal use only)
  56678. */
  56679. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56680. var offset = index * this._vertexBufferSize;
  56681. this._vertexData[offset] = particle.position.x;
  56682. this._vertexData[offset + 1] = particle.position.y;
  56683. this._vertexData[offset + 2] = particle.position.z;
  56684. this._vertexData[offset + 3] = particle.color.r;
  56685. this._vertexData[offset + 4] = particle.color.g;
  56686. this._vertexData[offset + 5] = particle.color.b;
  56687. this._vertexData[offset + 6] = particle.color.a;
  56688. this._vertexData[offset + 7] = particle.angle;
  56689. this._vertexData[offset + 8] = offsetX;
  56690. this._vertexData[offset + 9] = offsetY;
  56691. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56692. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56693. };
  56694. /**
  56695. * @hidden (for internal use only)
  56696. */
  56697. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56698. if (offsetX === 0)
  56699. offsetX = this._epsilon;
  56700. else if (offsetX === 1)
  56701. offsetX = 1 - this._epsilon;
  56702. if (offsetY === 0)
  56703. offsetY = this._epsilon;
  56704. else if (offsetY === 1)
  56705. offsetY = 1 - this._epsilon;
  56706. var offset = index * this._vertexBufferSize;
  56707. this._vertexData[offset] = particle.position.x;
  56708. this._vertexData[offset + 1] = particle.position.y;
  56709. this._vertexData[offset + 2] = particle.position.z;
  56710. this._vertexData[offset + 3] = particle.color.r;
  56711. this._vertexData[offset + 4] = particle.color.g;
  56712. this._vertexData[offset + 5] = particle.color.b;
  56713. this._vertexData[offset + 6] = particle.color.a;
  56714. this._vertexData[offset + 7] = particle.angle;
  56715. this._vertexData[offset + 8] = offsetX;
  56716. this._vertexData[offset + 9] = offsetY;
  56717. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  56718. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  56719. this._vertexData[offset + 12] = particle.cellIndex;
  56720. };
  56721. ParticleSystem.prototype._stopSubEmitters = function () {
  56722. if (!this.activeSubSystems) {
  56723. return;
  56724. }
  56725. this.activeSubSystems.forEach(function (subSystem) {
  56726. subSystem.stop(true);
  56727. });
  56728. this.activeSubSystems = new Array();
  56729. };
  56730. ParticleSystem.prototype._removeFromRoot = function () {
  56731. if (!this._rootParticleSystem) {
  56732. return;
  56733. }
  56734. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56735. if (index !== -1) {
  56736. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56737. }
  56738. };
  56739. // end of sub system methods
  56740. ParticleSystem.prototype._update = function (newParticles) {
  56741. // Update current
  56742. this._alive = this._particles.length > 0;
  56743. this.updateFunction(this._particles);
  56744. // Add new ones
  56745. var worldMatrix;
  56746. if (this.emitter.position) {
  56747. var emitterMesh = this.emitter;
  56748. worldMatrix = emitterMesh.getWorldMatrix();
  56749. }
  56750. else {
  56751. var emitterPosition = this.emitter;
  56752. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56753. }
  56754. var particle;
  56755. for (var index = 0; index < newParticles; index++) {
  56756. if (this._particles.length === this._capacity) {
  56757. break;
  56758. }
  56759. particle = this._createParticle();
  56760. this._particles.push(particle);
  56761. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56762. if (this.startPositionFunction) {
  56763. this.startPositionFunction(worldMatrix, particle.position, particle);
  56764. }
  56765. else {
  56766. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56767. }
  56768. if (this.startDirectionFunction) {
  56769. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56770. }
  56771. else {
  56772. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56773. }
  56774. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56775. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56776. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  56777. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56778. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56779. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56780. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56781. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56782. }
  56783. };
  56784. ParticleSystem.prototype._getEffect = function () {
  56785. if (this._customEffect) {
  56786. return this._customEffect;
  56787. }
  56788. ;
  56789. var defines = [];
  56790. if (this._scene.clipPlane) {
  56791. defines.push("#define CLIPPLANE");
  56792. }
  56793. if (this._isAnimationSheetEnabled) {
  56794. defines.push("#define ANIMATESHEET");
  56795. }
  56796. // Effect
  56797. var join = defines.join("\n");
  56798. if (this._cachedDefines !== join) {
  56799. this._cachedDefines = join;
  56800. var attributesNamesOrOptions;
  56801. var effectCreationOption;
  56802. if (this._isAnimationSheetEnabled) {
  56803. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  56804. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56805. }
  56806. else {
  56807. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  56808. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56809. }
  56810. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56811. }
  56812. return this._effect;
  56813. };
  56814. /**
  56815. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56816. */
  56817. ParticleSystem.prototype.animate = function () {
  56818. if (!this._started)
  56819. return;
  56820. var effect = this._getEffect();
  56821. // Check
  56822. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56823. return;
  56824. if (this._currentRenderId === this._scene.getRenderId()) {
  56825. return;
  56826. }
  56827. this._currentRenderId = this._scene.getRenderId();
  56828. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56829. // determine the number of particles we need to create
  56830. var newParticles;
  56831. if (this.manualEmitCount > -1) {
  56832. newParticles = this.manualEmitCount;
  56833. this._newPartsExcess = 0;
  56834. this.manualEmitCount = 0;
  56835. }
  56836. else {
  56837. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56838. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56839. }
  56840. if (this._newPartsExcess > 1.0) {
  56841. newParticles += this._newPartsExcess >> 0;
  56842. this._newPartsExcess -= this._newPartsExcess >> 0;
  56843. }
  56844. this._alive = false;
  56845. if (!this._stopped) {
  56846. this._actualFrame += this._scaledUpdateSpeed;
  56847. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56848. this.stop();
  56849. }
  56850. else {
  56851. newParticles = 0;
  56852. }
  56853. this._update(newParticles);
  56854. // Stopped?
  56855. if (this._stopped) {
  56856. if (!this._alive) {
  56857. this._started = false;
  56858. if (this.onAnimationEnd) {
  56859. this.onAnimationEnd();
  56860. }
  56861. if (this.disposeOnStop) {
  56862. this._scene._toBeDisposed.push(this);
  56863. }
  56864. }
  56865. }
  56866. // Animation sheet
  56867. if (this._isAnimationSheetEnabled) {
  56868. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56869. }
  56870. else {
  56871. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56872. }
  56873. // Update VBO
  56874. var offset = 0;
  56875. for (var index = 0; index < this._particles.length; index++) {
  56876. var particle = this._particles[index];
  56877. this._appendParticleVertexes(offset, particle);
  56878. offset += 4;
  56879. }
  56880. if (this._vertexBuffer) {
  56881. this._vertexBuffer.update(this._vertexData);
  56882. }
  56883. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56884. this.stop();
  56885. }
  56886. };
  56887. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56888. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56889. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56890. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56891. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56892. };
  56893. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56894. this._appendParticleVertex(offset++, particle, 0, 0);
  56895. this._appendParticleVertex(offset++, particle, 1, 0);
  56896. this._appendParticleVertex(offset++, particle, 1, 1);
  56897. this._appendParticleVertex(offset++, particle, 0, 1);
  56898. };
  56899. /**
  56900. * Rebuilds the particle system.
  56901. */
  56902. ParticleSystem.prototype.rebuild = function () {
  56903. this._createIndexBuffer();
  56904. if (this._vertexBuffer) {
  56905. this._vertexBuffer._rebuild();
  56906. }
  56907. };
  56908. /**
  56909. * Is this system ready to be used/rendered
  56910. * @return true if the system is ready
  56911. */
  56912. ParticleSystem.prototype.isReady = function () {
  56913. var effect = this._getEffect();
  56914. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56915. return false;
  56916. }
  56917. return true;
  56918. };
  56919. /**
  56920. * Renders the particle system in its current state.
  56921. * @returns the current number of particles
  56922. */
  56923. ParticleSystem.prototype.render = function () {
  56924. var effect = this._getEffect();
  56925. // Check
  56926. if (!this.isReady() || !this._particles.length) {
  56927. return 0;
  56928. }
  56929. var engine = this._scene.getEngine();
  56930. // Render
  56931. engine.enableEffect(effect);
  56932. engine.setState(false);
  56933. var viewMatrix = this._scene.getViewMatrix();
  56934. effect.setTexture("diffuseSampler", this.particleTexture);
  56935. effect.setMatrix("view", viewMatrix);
  56936. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56937. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56938. var baseSize = this.particleTexture.getBaseSize();
  56939. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56940. }
  56941. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56942. if (this._scene.clipPlane) {
  56943. var clipPlane = this._scene.clipPlane;
  56944. var invView = viewMatrix.clone();
  56945. invView.invert();
  56946. effect.setMatrix("invView", invView);
  56947. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56948. }
  56949. // VBOs
  56950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56951. // Draw order
  56952. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56953. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56954. }
  56955. else {
  56956. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56957. }
  56958. if (this.forceDepthWrite) {
  56959. engine.setDepthWrite(true);
  56960. }
  56961. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56962. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56963. return this._particles.length;
  56964. };
  56965. /**
  56966. * Disposes the particle system and free the associated resources
  56967. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56968. */
  56969. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56970. if (disposeTexture === void 0) { disposeTexture = true; }
  56971. if (this._vertexBuffer) {
  56972. this._vertexBuffer.dispose();
  56973. this._vertexBuffer = null;
  56974. }
  56975. if (this._indexBuffer) {
  56976. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56977. this._indexBuffer = null;
  56978. }
  56979. if (disposeTexture && this.particleTexture) {
  56980. this.particleTexture.dispose();
  56981. this.particleTexture = null;
  56982. }
  56983. this._removeFromRoot();
  56984. // Remove from scene
  56985. var index = this._scene.particleSystems.indexOf(this);
  56986. if (index > -1) {
  56987. this._scene.particleSystems.splice(index, 1);
  56988. }
  56989. // Callback
  56990. this.onDisposeObservable.notifyObservers(this);
  56991. this.onDisposeObservable.clear();
  56992. };
  56993. /**
  56994. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56995. * @param radius The radius of the sphere to emit from
  56996. * @returns the emitter
  56997. */
  56998. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56999. if (radius === void 0) { radius = 1; }
  57000. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  57001. this.particleEmitterType = particleEmitter;
  57002. return particleEmitter;
  57003. };
  57004. /**
  57005. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  57006. * @param radius The radius of the sphere to emit from
  57007. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57008. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57009. * @returns the emitter
  57010. */
  57011. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57012. if (radius === void 0) { radius = 1; }
  57013. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57014. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57015. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57016. this.particleEmitterType = particleEmitter;
  57017. return particleEmitter;
  57018. };
  57019. /**
  57020. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  57021. * @param radius The radius of the cone to emit from
  57022. * @param angle The base angle of the cone
  57023. * @returns the emitter
  57024. */
  57025. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57026. if (radius === void 0) { radius = 1; }
  57027. if (angle === void 0) { angle = Math.PI / 4; }
  57028. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57029. this.particleEmitterType = particleEmitter;
  57030. return particleEmitter;
  57031. };
  57032. // 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.
  57033. /**
  57034. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57035. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57036. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57037. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57038. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57039. * @returns the emitter
  57040. */
  57041. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57042. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57043. this.particleEmitterType = particleEmitter;
  57044. this.direction1 = direction1;
  57045. this.direction2 = direction2;
  57046. this.minEmitBox = minEmitBox;
  57047. this.maxEmitBox = maxEmitBox;
  57048. return particleEmitter;
  57049. };
  57050. // Clone
  57051. /**
  57052. * Clones the particle system.
  57053. * @param name The name of the cloned object
  57054. * @param newEmitter The new emitter to use
  57055. * @returns the cloned particle system
  57056. */
  57057. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57058. var custom = null;
  57059. var program = null;
  57060. if (this.customShader != null) {
  57061. program = this.customShader;
  57062. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57063. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57064. }
  57065. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57066. result.customShader = program;
  57067. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57068. if (newEmitter === undefined) {
  57069. newEmitter = this.emitter;
  57070. }
  57071. result.emitter = newEmitter;
  57072. if (this.particleTexture) {
  57073. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57074. }
  57075. if (!this.preventAutoStart) {
  57076. result.start();
  57077. }
  57078. return result;
  57079. };
  57080. /**
  57081. * Serializes the particle system to a JSON object.
  57082. * @returns the JSON object
  57083. */
  57084. ParticleSystem.prototype.serialize = function () {
  57085. var serializationObject = {};
  57086. serializationObject.name = this.name;
  57087. serializationObject.id = this.id;
  57088. // Emitter
  57089. if (this.emitter.position) {
  57090. var emitterMesh = this.emitter;
  57091. serializationObject.emitterId = emitterMesh.id;
  57092. }
  57093. else {
  57094. var emitterPosition = this.emitter;
  57095. serializationObject.emitter = emitterPosition.asArray();
  57096. }
  57097. serializationObject.capacity = this.getCapacity();
  57098. if (this.particleTexture) {
  57099. serializationObject.textureName = this.particleTexture.name;
  57100. }
  57101. // Animations
  57102. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57103. // Particle system
  57104. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57105. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57106. serializationObject.minSize = this.minSize;
  57107. serializationObject.maxSize = this.maxSize;
  57108. serializationObject.minScaleX = this.minScaleX;
  57109. serializationObject.maxScaleX = this.maxScaleX;
  57110. serializationObject.minScaleY = this.minScaleY;
  57111. serializationObject.maxScaleY = this.maxScaleY;
  57112. serializationObject.minEmitPower = this.minEmitPower;
  57113. serializationObject.maxEmitPower = this.maxEmitPower;
  57114. serializationObject.minLifeTime = this.minLifeTime;
  57115. serializationObject.maxLifeTime = this.maxLifeTime;
  57116. serializationObject.emitRate = this.emitRate;
  57117. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57118. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57119. serializationObject.gravity = this.gravity.asArray();
  57120. serializationObject.direction1 = this.direction1.asArray();
  57121. serializationObject.direction2 = this.direction2.asArray();
  57122. serializationObject.color1 = this.color1.asArray();
  57123. serializationObject.color2 = this.color2.asArray();
  57124. serializationObject.colorDead = this.colorDead.asArray();
  57125. serializationObject.updateSpeed = this.updateSpeed;
  57126. serializationObject.targetStopDuration = this.targetStopDuration;
  57127. serializationObject.textureMask = this.textureMask.asArray();
  57128. serializationObject.blendMode = this.blendMode;
  57129. serializationObject.customShader = this.customShader;
  57130. serializationObject.preventAutoStart = this.preventAutoStart;
  57131. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57132. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57133. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57134. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57135. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57136. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57137. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57138. // Emitter
  57139. if (this.particleEmitterType) {
  57140. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57141. }
  57142. return serializationObject;
  57143. };
  57144. /**
  57145. * Parses a JSON object to create a particle system.
  57146. * @param parsedParticleSystem The JSON object to parse
  57147. * @param scene The scene to create the particle system in
  57148. * @param rootUrl The root url to use to load external dependencies like texture
  57149. * @returns the Parsed particle system
  57150. */
  57151. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57152. var name = parsedParticleSystem.name;
  57153. var custom = null;
  57154. var program = null;
  57155. if (parsedParticleSystem.customShader) {
  57156. program = parsedParticleSystem.customShader;
  57157. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57158. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57159. }
  57160. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57161. particleSystem.customShader = program;
  57162. if (parsedParticleSystem.id) {
  57163. particleSystem.id = parsedParticleSystem.id;
  57164. }
  57165. // Auto start
  57166. if (parsedParticleSystem.preventAutoStart) {
  57167. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57168. }
  57169. // Texture
  57170. if (parsedParticleSystem.textureName) {
  57171. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57172. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57173. }
  57174. // Emitter
  57175. if (parsedParticleSystem.emitterId) {
  57176. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57177. }
  57178. else {
  57179. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57180. }
  57181. // Animations
  57182. if (parsedParticleSystem.animations) {
  57183. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57184. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57185. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57186. }
  57187. }
  57188. if (parsedParticleSystem.autoAnimate) {
  57189. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57190. }
  57191. // Particle system
  57192. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57193. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57194. particleSystem.minSize = parsedParticleSystem.minSize;
  57195. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57196. if (parsedParticleSystem.minScaleX) {
  57197. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57198. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57199. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57200. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57201. }
  57202. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57203. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57204. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57205. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57206. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57207. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57208. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57209. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57210. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57211. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57212. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57213. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57214. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57215. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57216. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57217. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57218. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57219. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57220. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57221. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57222. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57223. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57224. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57225. if (!particleSystem.preventAutoStart) {
  57226. particleSystem.start();
  57227. }
  57228. return particleSystem;
  57229. };
  57230. /**
  57231. * Source color is added to the destination color without alpha affecting the result.
  57232. */
  57233. ParticleSystem.BLENDMODE_ONEONE = 0;
  57234. /**
  57235. * Blend current color and particle color using particle’s alpha.
  57236. */
  57237. ParticleSystem.BLENDMODE_STANDARD = 1;
  57238. return ParticleSystem;
  57239. }());
  57240. BABYLON.ParticleSystem = ParticleSystem;
  57241. })(BABYLON || (BABYLON = {}));
  57242. //# sourceMappingURL=babylon.particleSystem.js.map
  57243. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57244. var BABYLON;
  57245. (function (BABYLON) {
  57246. /**
  57247. * Particle emitter emitting particles from the inside of a box.
  57248. * It emits the particles randomly between 2 given directions.
  57249. */
  57250. var BoxParticleEmitter = /** @class */ (function () {
  57251. /**
  57252. * Creates a new instance BoxParticleEmitter
  57253. */
  57254. function BoxParticleEmitter() {
  57255. /**
  57256. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57257. */
  57258. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57259. /**
  57260. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57261. */
  57262. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57263. /**
  57264. * 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.
  57265. */
  57266. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57267. /**
  57268. * 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.
  57269. */
  57270. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57271. }
  57272. /**
  57273. * Called by the particle System when the direction is computed for the created particle.
  57274. * @param emitPower is the power of the particle (speed)
  57275. * @param worldMatrix is the world matrix of the particle system
  57276. * @param directionToUpdate is the direction vector to update with the result
  57277. * @param particle is the particle we are computed the direction for
  57278. */
  57279. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57280. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57281. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57282. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57283. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57284. };
  57285. /**
  57286. * Called by the particle System when the position is computed for the created particle.
  57287. * @param worldMatrix is the world matrix of the particle system
  57288. * @param positionToUpdate is the position vector to update with the result
  57289. * @param particle is the particle we are computed the position for
  57290. */
  57291. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57292. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57293. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57294. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57296. };
  57297. /**
  57298. * Clones the current emitter and returns a copy of it
  57299. * @returns the new emitter
  57300. */
  57301. BoxParticleEmitter.prototype.clone = function () {
  57302. var newOne = new BoxParticleEmitter();
  57303. BABYLON.Tools.DeepCopy(this, newOne);
  57304. return newOne;
  57305. };
  57306. /**
  57307. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57308. * @param effect defines the update shader
  57309. */
  57310. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57311. effect.setVector3("direction1", this.direction1);
  57312. effect.setVector3("direction2", this.direction2);
  57313. effect.setVector3("minEmitBox", this.minEmitBox);
  57314. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57315. };
  57316. /**
  57317. * Returns a string to use to update the GPU particles update shader
  57318. * @returns a string containng the defines string
  57319. */
  57320. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57321. return "#define BOXEMITTER";
  57322. };
  57323. /**
  57324. * Returns the string "BoxEmitter"
  57325. * @returns a string containing the class name
  57326. */
  57327. BoxParticleEmitter.prototype.getClassName = function () {
  57328. return "BoxEmitter";
  57329. };
  57330. /**
  57331. * Serializes the particle system to a JSON object.
  57332. * @returns the JSON object
  57333. */
  57334. BoxParticleEmitter.prototype.serialize = function () {
  57335. var serializationObject = {};
  57336. serializationObject.type = this.getClassName();
  57337. serializationObject.direction1 = this.direction1.asArray();
  57338. serializationObject.direction2 = this.direction2.asArray();
  57339. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57340. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57341. return serializationObject;
  57342. };
  57343. /**
  57344. * Parse properties from a JSON object
  57345. * @param serializationObject defines the JSON object
  57346. */
  57347. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57348. this.direction1.copyFrom(serializationObject.direction1);
  57349. this.direction2.copyFrom(serializationObject.direction2);
  57350. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57351. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57352. };
  57353. return BoxParticleEmitter;
  57354. }());
  57355. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57356. })(BABYLON || (BABYLON = {}));
  57357. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57358. var BABYLON;
  57359. (function (BABYLON) {
  57360. /**
  57361. * Particle emitter emitting particles from the inside of a cone.
  57362. * It emits the particles alongside the cone volume from the base to the particle.
  57363. * The emission direction might be randomized.
  57364. */
  57365. var ConeParticleEmitter = /** @class */ (function () {
  57366. /**
  57367. * Creates a new instance ConeParticleEmitter
  57368. * @param radius the radius of the emission cone (1 by default)
  57369. * @param angles the cone base angle (PI by default)
  57370. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57371. */
  57372. function ConeParticleEmitter(radius, angle,
  57373. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57374. directionRandomizer) {
  57375. if (radius === void 0) { radius = 1; }
  57376. if (angle === void 0) { angle = Math.PI; }
  57377. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57378. this.directionRandomizer = directionRandomizer;
  57379. this.angle = angle;
  57380. this.radius = radius;
  57381. }
  57382. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57383. /**
  57384. * Gets or sets the radius of the emission cone
  57385. */
  57386. get: function () {
  57387. return this._radius;
  57388. },
  57389. set: function (value) {
  57390. this._radius = value;
  57391. this._buildHeight();
  57392. },
  57393. enumerable: true,
  57394. configurable: true
  57395. });
  57396. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57397. /**
  57398. * Gets or sets the angle of the emission cone
  57399. */
  57400. get: function () {
  57401. return this._angle;
  57402. },
  57403. set: function (value) {
  57404. this._angle = value;
  57405. this._buildHeight();
  57406. },
  57407. enumerable: true,
  57408. configurable: true
  57409. });
  57410. ConeParticleEmitter.prototype._buildHeight = function () {
  57411. if (this._angle !== 0) {
  57412. this._height = this._radius / Math.tan(this._angle / 2);
  57413. }
  57414. else {
  57415. this._height = 1;
  57416. }
  57417. };
  57418. /**
  57419. * Called by the particle System when the direction is computed for the created particle.
  57420. * @param emitPower is the power of the particle (speed)
  57421. * @param worldMatrix is the world matrix of the particle system
  57422. * @param directionToUpdate is the direction vector to update with the result
  57423. * @param particle is the particle we are computed the direction for
  57424. */
  57425. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57426. if (this._angle === 0) {
  57427. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57428. }
  57429. else {
  57430. // measure the direction Vector from the emitter to the particle.
  57431. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57432. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57433. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57434. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57435. direction.x += randX;
  57436. direction.y += randY;
  57437. direction.z += randZ;
  57438. direction.normalize();
  57439. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57440. }
  57441. };
  57442. /**
  57443. * Called by the particle System when the position is computed for the created particle.
  57444. * @param worldMatrix is the world matrix of the particle system
  57445. * @param positionToUpdate is the position vector to update with the result
  57446. * @param particle is the particle we are computed the position for
  57447. */
  57448. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57449. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57450. var h = BABYLON.Scalar.RandomRange(0, 1);
  57451. // Better distribution in a cone at normal angles.
  57452. h = 1 - h * h;
  57453. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57454. radius = radius * h;
  57455. var randX = radius * Math.sin(s);
  57456. var randZ = radius * Math.cos(s);
  57457. var randY = h * this._height;
  57458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57459. };
  57460. /**
  57461. * Clones the current emitter and returns a copy of it
  57462. * @returns the new emitter
  57463. */
  57464. ConeParticleEmitter.prototype.clone = function () {
  57465. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57466. BABYLON.Tools.DeepCopy(this, newOne);
  57467. return newOne;
  57468. };
  57469. /**
  57470. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57471. * @param effect defines the update shader
  57472. */
  57473. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57474. effect.setFloat("radius", this._radius);
  57475. effect.setFloat("coneAngle", this._angle);
  57476. effect.setFloat("height", this._height);
  57477. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57478. };
  57479. /**
  57480. * Returns a string to use to update the GPU particles update shader
  57481. * @returns a string containng the defines string
  57482. */
  57483. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57484. return "#define CONEEMITTER";
  57485. };
  57486. /**
  57487. * Returns the string "BoxEmitter"
  57488. * @returns a string containing the class name
  57489. */
  57490. ConeParticleEmitter.prototype.getClassName = function () {
  57491. return "ConeEmitter";
  57492. };
  57493. /**
  57494. * Serializes the particle system to a JSON object.
  57495. * @returns the JSON object
  57496. */
  57497. ConeParticleEmitter.prototype.serialize = function () {
  57498. var serializationObject = {};
  57499. serializationObject.type = this.getClassName();
  57500. serializationObject.radius = this._radius;
  57501. serializationObject.angle = this._angle;
  57502. serializationObject.directionRandomizer = this.directionRandomizer;
  57503. return serializationObject;
  57504. };
  57505. /**
  57506. * Parse properties from a JSON object
  57507. * @param serializationObject defines the JSON object
  57508. */
  57509. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57510. this.radius = serializationObject.radius;
  57511. this.angle = serializationObject.angle;
  57512. this.directionRandomizer = serializationObject.directionRandomizer;
  57513. };
  57514. return ConeParticleEmitter;
  57515. }());
  57516. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57517. })(BABYLON || (BABYLON = {}));
  57518. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57519. var BABYLON;
  57520. (function (BABYLON) {
  57521. /**
  57522. * Particle emitter emitting particles from the inside of a sphere.
  57523. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57524. */
  57525. var SphereParticleEmitter = /** @class */ (function () {
  57526. /**
  57527. * Creates a new instance SphereParticleEmitter
  57528. * @param radius the radius of the emission sphere (1 by default)
  57529. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57530. */
  57531. function SphereParticleEmitter(
  57532. /**
  57533. * The radius of the emission sphere.
  57534. */
  57535. radius,
  57536. /**
  57537. * How much to randomize the particle direction [0-1].
  57538. */
  57539. directionRandomizer) {
  57540. if (radius === void 0) { radius = 1; }
  57541. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57542. this.radius = radius;
  57543. this.directionRandomizer = directionRandomizer;
  57544. }
  57545. /**
  57546. * Called by the particle System when the direction is computed for the created particle.
  57547. * @param emitPower is the power of the particle (speed)
  57548. * @param worldMatrix is the world matrix of the particle system
  57549. * @param directionToUpdate is the direction vector to update with the result
  57550. * @param particle is the particle we are computed the direction for
  57551. */
  57552. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57553. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57554. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57555. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57556. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57557. direction.x += randX;
  57558. direction.y += randY;
  57559. direction.z += randZ;
  57560. direction.normalize();
  57561. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57562. };
  57563. /**
  57564. * Called by the particle System when the position is computed for the created particle.
  57565. * @param worldMatrix is the world matrix of the particle system
  57566. * @param positionToUpdate is the position vector to update with the result
  57567. * @param particle is the particle we are computed the position for
  57568. */
  57569. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57570. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57571. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57572. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57573. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57574. var randY = randRadius * Math.cos(theta);
  57575. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57576. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57577. };
  57578. /**
  57579. * Clones the current emitter and returns a copy of it
  57580. * @returns the new emitter
  57581. */
  57582. SphereParticleEmitter.prototype.clone = function () {
  57583. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57584. BABYLON.Tools.DeepCopy(this, newOne);
  57585. return newOne;
  57586. };
  57587. /**
  57588. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57589. * @param effect defines the update shader
  57590. */
  57591. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57592. effect.setFloat("radius", this.radius);
  57593. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57594. };
  57595. /**
  57596. * Returns a string to use to update the GPU particles update shader
  57597. * @returns a string containng the defines string
  57598. */
  57599. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57600. return "#define SPHEREEMITTER";
  57601. };
  57602. /**
  57603. * Returns the string "SphereParticleEmitter"
  57604. * @returns a string containing the class name
  57605. */
  57606. SphereParticleEmitter.prototype.getClassName = function () {
  57607. return "SphereParticleEmitter";
  57608. };
  57609. /**
  57610. * Serializes the particle system to a JSON object.
  57611. * @returns the JSON object
  57612. */
  57613. SphereParticleEmitter.prototype.serialize = function () {
  57614. var serializationObject = {};
  57615. serializationObject.type = this.getClassName();
  57616. serializationObject.radius = this.radius;
  57617. serializationObject.directionRandomizer = this.directionRandomizer;
  57618. return serializationObject;
  57619. };
  57620. /**
  57621. * Parse properties from a JSON object
  57622. * @param serializationObject defines the JSON object
  57623. */
  57624. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57625. this.radius = serializationObject.radius;
  57626. this.directionRandomizer = serializationObject.directionRandomizer;
  57627. };
  57628. return SphereParticleEmitter;
  57629. }());
  57630. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57631. /**
  57632. * Particle emitter emitting particles from the inside of a sphere.
  57633. * It emits the particles randomly between two vectors.
  57634. */
  57635. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57636. __extends(SphereDirectedParticleEmitter, _super);
  57637. /**
  57638. * Creates a new instance SphereDirectedParticleEmitter
  57639. * @param radius the radius of the emission sphere (1 by default)
  57640. * @param direction1 the min limit of the emission direction (up vector by default)
  57641. * @param direction2 the max limit of the emission direction (up vector by default)
  57642. */
  57643. function SphereDirectedParticleEmitter(radius,
  57644. /**
  57645. * The min limit of the emission direction.
  57646. */
  57647. direction1,
  57648. /**
  57649. * The max limit of the emission direction.
  57650. */
  57651. direction2) {
  57652. if (radius === void 0) { radius = 1; }
  57653. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57654. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57655. var _this = _super.call(this, radius) || this;
  57656. _this.direction1 = direction1;
  57657. _this.direction2 = direction2;
  57658. return _this;
  57659. }
  57660. /**
  57661. * Called by the particle System when the direction is computed for the created particle.
  57662. * @param emitPower is the power of the particle (speed)
  57663. * @param worldMatrix is the world matrix of the particle system
  57664. * @param directionToUpdate is the direction vector to update with the result
  57665. * @param particle is the particle we are computed the direction for
  57666. */
  57667. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57668. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57669. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57670. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57671. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57672. };
  57673. /**
  57674. * Clones the current emitter and returns a copy of it
  57675. * @returns the new emitter
  57676. */
  57677. SphereDirectedParticleEmitter.prototype.clone = function () {
  57678. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57679. BABYLON.Tools.DeepCopy(this, newOne);
  57680. return newOne;
  57681. };
  57682. /**
  57683. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57684. * @param effect defines the update shader
  57685. */
  57686. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57687. effect.setFloat("radius", this.radius);
  57688. effect.setVector3("direction1", this.direction1);
  57689. effect.setVector3("direction2", this.direction2);
  57690. };
  57691. /**
  57692. * Returns a string to use to update the GPU particles update shader
  57693. * @returns a string containng the defines string
  57694. */
  57695. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57696. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57697. };
  57698. /**
  57699. * Returns the string "SphereDirectedParticleEmitter"
  57700. * @returns a string containing the class name
  57701. */
  57702. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57703. return "SphereDirectedParticleEmitter";
  57704. };
  57705. /**
  57706. * Serializes the particle system to a JSON object.
  57707. * @returns the JSON object
  57708. */
  57709. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57710. var serializationObject = _super.prototype.serialize.call(this);
  57711. serializationObject.direction1 = this.direction1.asArray();
  57712. serializationObject.direction2 = this.direction2.asArray();
  57713. return serializationObject;
  57714. };
  57715. /**
  57716. * Parse properties from a JSON object
  57717. * @param serializationObject defines the JSON object
  57718. */
  57719. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57720. _super.prototype.parse.call(this, serializationObject);
  57721. this.direction1.copyFrom(serializationObject.direction1);
  57722. this.direction2.copyFrom(serializationObject.direction2);
  57723. };
  57724. return SphereDirectedParticleEmitter;
  57725. }(SphereParticleEmitter));
  57726. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57727. })(BABYLON || (BABYLON = {}));
  57728. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57729. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57730. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57731. s = arguments[i];
  57732. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57733. t[p] = s[p];
  57734. }
  57735. return t;
  57736. };
  57737. var BABYLON;
  57738. (function (BABYLON) {
  57739. /**
  57740. * This represents a GPU particle system in Babylon
  57741. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57742. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57743. */
  57744. var GPUParticleSystem = /** @class */ (function () {
  57745. /**
  57746. * Instantiates a GPU particle system.
  57747. * 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.
  57748. * @param name The name of the particle system
  57749. * @param capacity The max number of particles alive at the same time
  57750. * @param scene The scene the particle system belongs to
  57751. */
  57752. function GPUParticleSystem(name, options, scene) {
  57753. /**
  57754. * The emitter represents the Mesh or position we are attaching the particle system to.
  57755. */
  57756. this.emitter = null;
  57757. /**
  57758. * The rendering group used by the Particle system to chose when to render.
  57759. */
  57760. this.renderingGroupId = 0;
  57761. /**
  57762. * The layer mask we are rendering the particles through.
  57763. */
  57764. this.layerMask = 0x0FFFFFFF;
  57765. this._targetIndex = 0;
  57766. this._currentRenderId = -1;
  57767. this._started = false;
  57768. this._stopped = false;
  57769. this._timeDelta = 0;
  57770. this._attributesStrideSize = 18;
  57771. this._actualFrame = 0;
  57772. /**
  57773. * List of animations used by the particle system.
  57774. */
  57775. this.animations = [];
  57776. /**
  57777. * An event triggered when the system is disposed.
  57778. */
  57779. this.onDisposeObservable = new BABYLON.Observable();
  57780. /**
  57781. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57782. */
  57783. this.updateSpeed = 0.01;
  57784. /**
  57785. * The amount of time the particle system is running (depends of the overall update speed).
  57786. */
  57787. this.targetStopDuration = 0;
  57788. /**
  57789. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57790. */
  57791. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57792. /**
  57793. * Minimum life time of emitting particles.
  57794. */
  57795. this.minLifeTime = 1;
  57796. /**
  57797. * Maximum life time of emitting particles.
  57798. */
  57799. this.maxLifeTime = 1;
  57800. /**
  57801. * Minimum Size of emitting particles.
  57802. */
  57803. this.minSize = 1;
  57804. /**
  57805. * Maximum Size of emitting particles.
  57806. */
  57807. this.maxSize = 1;
  57808. /**
  57809. * Minimum scale of emitting particles on X axis.
  57810. */
  57811. this.minScaleX = 1;
  57812. /**
  57813. * Maximum scale of emitting particles on X axis.
  57814. */
  57815. this.maxScaleX = 1;
  57816. /**
  57817. * Minimum scale of emitting particles on Y axis.
  57818. */
  57819. this.minScaleY = 1;
  57820. /**
  57821. * Maximum scale of emitting particles on Y axis.
  57822. */
  57823. this.maxScaleY = 1;
  57824. /**
  57825. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57826. */
  57827. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57828. /**
  57829. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57830. */
  57831. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57832. /**
  57833. * Color the particle will have at the end of its lifetime.
  57834. */
  57835. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57836. /**
  57837. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57838. */
  57839. this.emitRate = 100;
  57840. /**
  57841. * You can use gravity if you want to give an orientation to your particles.
  57842. */
  57843. this.gravity = BABYLON.Vector3.Zero();
  57844. /**
  57845. * Minimum power of emitting particles.
  57846. */
  57847. this.minEmitPower = 1;
  57848. /**
  57849. * Maximum power of emitting particles.
  57850. */
  57851. this.maxEmitPower = 1;
  57852. /**
  57853. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57854. */
  57855. this.minAngularSpeed = 0;
  57856. /**
  57857. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57858. */
  57859. this.maxAngularSpeed = 0;
  57860. /**
  57861. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57862. * to override the particles.
  57863. */
  57864. this.forceDepthWrite = false;
  57865. this.id = name;
  57866. this.name = name;
  57867. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57868. this._engine = this._scene.getEngine();
  57869. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57870. this._capacity = fullOptions.capacity;
  57871. this._activeCount = fullOptions.capacity;
  57872. this._currentActiveCount = 0;
  57873. this._scene.particleSystems.push(this);
  57874. this._updateEffectOptions = {
  57875. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57876. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57877. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57878. "angleRange"],
  57879. uniformBuffersNames: [],
  57880. samplers: ["randomSampler"],
  57881. defines: "",
  57882. fallbacks: null,
  57883. onCompiled: null,
  57884. onError: null,
  57885. indexParameters: null,
  57886. maxSimultaneousLights: 0,
  57887. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57888. };
  57889. // Random data
  57890. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57891. var d = [];
  57892. for (var i = 0; i < maxTextureSize; ++i) {
  57893. d.push(Math.random());
  57894. d.push(Math.random());
  57895. d.push(Math.random());
  57896. d.push(Math.random());
  57897. }
  57898. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57899. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57900. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57901. this._randomTextureSize = maxTextureSize;
  57902. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57903. }
  57904. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57905. /**
  57906. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57907. */
  57908. get: function () {
  57909. if (!BABYLON.Engine.LastCreatedEngine) {
  57910. return false;
  57911. }
  57912. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57913. },
  57914. enumerable: true,
  57915. configurable: true
  57916. });
  57917. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57918. /**
  57919. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57920. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57921. */
  57922. get: function () {
  57923. if (this.particleEmitterType.direction1) {
  57924. return this.particleEmitterType.direction1;
  57925. }
  57926. return BABYLON.Vector3.Zero();
  57927. },
  57928. set: function (value) {
  57929. if (this.particleEmitterType.direction1) {
  57930. this.particleEmitterType.direction1 = value;
  57931. }
  57932. },
  57933. enumerable: true,
  57934. configurable: true
  57935. });
  57936. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57937. /**
  57938. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57939. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57940. */
  57941. get: function () {
  57942. if (this.particleEmitterType.direction2) {
  57943. return this.particleEmitterType.direction2;
  57944. }
  57945. return BABYLON.Vector3.Zero();
  57946. },
  57947. set: function (value) {
  57948. if (this.particleEmitterType.direction2) {
  57949. this.particleEmitterType.direction2 = value;
  57950. }
  57951. },
  57952. enumerable: true,
  57953. configurable: true
  57954. });
  57955. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57956. /**
  57957. * 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.
  57958. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57959. */
  57960. get: function () {
  57961. if (this.particleEmitterType.minEmitBox) {
  57962. return this.particleEmitterType.minEmitBox;
  57963. }
  57964. return BABYLON.Vector3.Zero();
  57965. },
  57966. set: function (value) {
  57967. if (this.particleEmitterType.minEmitBox) {
  57968. this.particleEmitterType.minEmitBox = value;
  57969. }
  57970. },
  57971. enumerable: true,
  57972. configurable: true
  57973. });
  57974. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57975. /**
  57976. * 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.
  57977. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57978. */
  57979. get: function () {
  57980. if (this.particleEmitterType.maxEmitBox) {
  57981. return this.particleEmitterType.maxEmitBox;
  57982. }
  57983. return BABYLON.Vector3.Zero();
  57984. },
  57985. set: function (value) {
  57986. if (this.particleEmitterType.maxEmitBox) {
  57987. this.particleEmitterType.maxEmitBox = value;
  57988. }
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. /**
  57994. * Gets the maximum number of particles active at the same time.
  57995. * @returns The max number of active particles.
  57996. */
  57997. GPUParticleSystem.prototype.getCapacity = function () {
  57998. return this._capacity;
  57999. };
  58000. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  58001. /**
  58002. * Gets or set the number of active particles
  58003. */
  58004. get: function () {
  58005. return this._activeCount;
  58006. },
  58007. set: function (value) {
  58008. this._activeCount = Math.min(value, this._capacity);
  58009. },
  58010. enumerable: true,
  58011. configurable: true
  58012. });
  58013. /**
  58014. * Is this system ready to be used/rendered
  58015. * @return true if the system is ready
  58016. */
  58017. GPUParticleSystem.prototype.isReady = function () {
  58018. if (!this._updateEffect) {
  58019. this._recreateUpdateEffect();
  58020. this._recreateRenderEffect();
  58021. return false;
  58022. }
  58023. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58024. return false;
  58025. }
  58026. return true;
  58027. };
  58028. /**
  58029. * Gets Wether the system has been started.
  58030. * @returns True if it has been started, otherwise false.
  58031. */
  58032. GPUParticleSystem.prototype.isStarted = function () {
  58033. return this._started;
  58034. };
  58035. /**
  58036. * Starts the particle system and begins to emit.
  58037. */
  58038. GPUParticleSystem.prototype.start = function () {
  58039. this._started = true;
  58040. this._stopped = false;
  58041. };
  58042. /**
  58043. * Stops the particle system.
  58044. */
  58045. GPUParticleSystem.prototype.stop = function () {
  58046. this._stopped = true;
  58047. };
  58048. /**
  58049. * Remove all active particles
  58050. */
  58051. GPUParticleSystem.prototype.reset = function () {
  58052. this._releaseBuffers();
  58053. this._releaseVAOs();
  58054. this._currentActiveCount = 0;
  58055. this._targetIndex = 0;
  58056. };
  58057. /**
  58058. * Returns the string "GPUParticleSystem"
  58059. * @returns a string containing the class name
  58060. */
  58061. GPUParticleSystem.prototype.getClassName = function () {
  58062. return "GPUParticleSystem";
  58063. };
  58064. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  58065. var updateVertexBuffers = {};
  58066. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  58067. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  58068. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  58069. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  58070. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  58071. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  58072. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  58073. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  58074. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58075. this._engine.bindArrayBuffer(null);
  58076. return vao;
  58077. };
  58078. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58079. var renderVertexBuffers = {};
  58080. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58081. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58082. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58083. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  58084. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  58085. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  58086. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58087. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58088. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58089. this._engine.bindArrayBuffer(null);
  58090. return vao;
  58091. };
  58092. GPUParticleSystem.prototype._initialize = function (force) {
  58093. if (force === void 0) { force = false; }
  58094. if (this._buffer0 && !force) {
  58095. return;
  58096. }
  58097. var engine = this._scene.getEngine();
  58098. var data = new Array();
  58099. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58100. // position
  58101. data.push(0.0);
  58102. data.push(0.0);
  58103. data.push(0.0);
  58104. // Age and life
  58105. data.push(0.0); // create the particle as a dead one to create a new one at start
  58106. data.push(0.0);
  58107. // Seed
  58108. data.push(Math.random());
  58109. // Size
  58110. data.push(0.0);
  58111. data.push(0.0);
  58112. data.push(0.0);
  58113. // color
  58114. data.push(0.0);
  58115. data.push(0.0);
  58116. data.push(0.0);
  58117. data.push(0.0);
  58118. // direction
  58119. data.push(0.0);
  58120. data.push(0.0);
  58121. data.push(0.0);
  58122. // angle
  58123. data.push(0.0);
  58124. data.push(0.0);
  58125. }
  58126. // Sprite data
  58127. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58128. -0.5, 0.5, 0, 1,
  58129. -0.5, -0.5, 0, 0,
  58130. 0.5, -0.5, 1, 0]);
  58131. // Buffers
  58132. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58133. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58134. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58135. // Update VAO
  58136. this._updateVAO = [];
  58137. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58138. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58139. // Render VAO
  58140. this._renderVAO = [];
  58141. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58142. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58143. // Links
  58144. this._sourceBuffer = this._buffer0;
  58145. this._targetBuffer = this._buffer1;
  58146. };
  58147. /** @hidden */
  58148. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58149. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58150. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58151. return;
  58152. }
  58153. this._updateEffectOptions.defines = defines;
  58154. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58155. };
  58156. /** @hidden */
  58157. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58158. var defines = "";
  58159. if (this._scene.clipPlane) {
  58160. defines = "\n#define CLIPPLANE";
  58161. }
  58162. if (this._renderEffect && this._renderEffect.defines === defines) {
  58163. return;
  58164. }
  58165. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58166. };
  58167. /**
  58168. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58169. */
  58170. GPUParticleSystem.prototype.animate = function () {
  58171. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58172. this._actualFrame += this._timeDelta;
  58173. if (!this._stopped) {
  58174. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58175. this.stop();
  58176. }
  58177. }
  58178. };
  58179. /**
  58180. * Renders the particle system in its current state.
  58181. * @returns the current number of particles
  58182. */
  58183. GPUParticleSystem.prototype.render = function () {
  58184. if (!this._started) {
  58185. return 0;
  58186. }
  58187. this._recreateUpdateEffect();
  58188. this._recreateRenderEffect();
  58189. if (!this.isReady()) {
  58190. return 0;
  58191. }
  58192. if (this._currentRenderId === this._scene.getRenderId()) {
  58193. return 0;
  58194. }
  58195. this._currentRenderId = this._scene.getRenderId();
  58196. // Get everything ready to render
  58197. this._initialize();
  58198. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58199. // Enable update effect
  58200. this._engine.enableEffect(this._updateEffect);
  58201. this._engine.setState(false);
  58202. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58203. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58204. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58205. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58206. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58207. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58208. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58209. this._updateEffect.setDirectColor4("color1", this.color1);
  58210. this._updateEffect.setDirectColor4("color2", this.color2);
  58211. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58212. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58213. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58214. this._updateEffect.setVector3("gravity", this.gravity);
  58215. if (this.particleEmitterType) {
  58216. this.particleEmitterType.applyToShader(this._updateEffect);
  58217. }
  58218. var emitterWM;
  58219. if (this.emitter.position) {
  58220. var emitterMesh = this.emitter;
  58221. emitterWM = emitterMesh.getWorldMatrix();
  58222. }
  58223. else {
  58224. var emitterPosition = this.emitter;
  58225. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58226. }
  58227. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58228. // Bind source VAO
  58229. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58230. // Update
  58231. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58232. this._engine.setRasterizerState(false);
  58233. this._engine.beginTransformFeedback();
  58234. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58235. this._engine.endTransformFeedback();
  58236. this._engine.setRasterizerState(true);
  58237. this._engine.bindTransformFeedbackBuffer(null);
  58238. // Enable render effect
  58239. this._engine.enableEffect(this._renderEffect);
  58240. var viewMatrix = this._scene.getViewMatrix();
  58241. this._renderEffect.setMatrix("view", viewMatrix);
  58242. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58243. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58244. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58245. if (this._scene.clipPlane) {
  58246. var clipPlane = this._scene.clipPlane;
  58247. var invView = viewMatrix.clone();
  58248. invView.invert();
  58249. this._renderEffect.setMatrix("invView", invView);
  58250. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58251. }
  58252. // Draw order
  58253. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58254. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58255. }
  58256. else {
  58257. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58258. }
  58259. if (this.forceDepthWrite) {
  58260. this._engine.setDepthWrite(true);
  58261. }
  58262. // Bind source VAO
  58263. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58264. // Render
  58265. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58266. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58267. // Switch VAOs
  58268. this._targetIndex++;
  58269. if (this._targetIndex === 2) {
  58270. this._targetIndex = 0;
  58271. }
  58272. // Switch buffers
  58273. var tmpBuffer = this._sourceBuffer;
  58274. this._sourceBuffer = this._targetBuffer;
  58275. this._targetBuffer = tmpBuffer;
  58276. return this._currentActiveCount;
  58277. };
  58278. /**
  58279. * Rebuilds the particle system
  58280. */
  58281. GPUParticleSystem.prototype.rebuild = function () {
  58282. this._initialize(true);
  58283. };
  58284. GPUParticleSystem.prototype._releaseBuffers = function () {
  58285. if (this._buffer0) {
  58286. this._buffer0.dispose();
  58287. this._buffer0 = null;
  58288. }
  58289. if (this._buffer1) {
  58290. this._buffer1.dispose();
  58291. this._buffer1 = null;
  58292. }
  58293. if (this._spriteBuffer) {
  58294. this._spriteBuffer.dispose();
  58295. this._spriteBuffer = null;
  58296. }
  58297. };
  58298. GPUParticleSystem.prototype._releaseVAOs = function () {
  58299. if (!this._updateVAO) {
  58300. return;
  58301. }
  58302. for (var index = 0; index < this._updateVAO.length; index++) {
  58303. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58304. }
  58305. this._updateVAO = [];
  58306. for (var index = 0; index < this._renderVAO.length; index++) {
  58307. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58308. }
  58309. this._renderVAO = [];
  58310. };
  58311. /**
  58312. * Disposes the particle system and free the associated resources
  58313. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58314. */
  58315. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58316. if (disposeTexture === void 0) { disposeTexture = true; }
  58317. var index = this._scene.particleSystems.indexOf(this);
  58318. if (index > -1) {
  58319. this._scene.particleSystems.splice(index, 1);
  58320. }
  58321. this._releaseBuffers();
  58322. this._releaseVAOs();
  58323. if (this._randomTexture) {
  58324. this._randomTexture.dispose();
  58325. this._randomTexture = null;
  58326. }
  58327. if (disposeTexture && this.particleTexture) {
  58328. this.particleTexture.dispose();
  58329. this.particleTexture = null;
  58330. }
  58331. // Callback
  58332. this.onDisposeObservable.notifyObservers(this);
  58333. this.onDisposeObservable.clear();
  58334. };
  58335. /**
  58336. * Clones the particle system.
  58337. * @param name The name of the cloned object
  58338. * @param newEmitter The new emitter to use
  58339. * @returns the cloned particle system
  58340. */
  58341. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58342. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58343. BABYLON.Tools.DeepCopy(this, result);
  58344. if (newEmitter === undefined) {
  58345. newEmitter = this.emitter;
  58346. }
  58347. result.emitter = newEmitter;
  58348. if (this.particleTexture) {
  58349. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58350. }
  58351. return result;
  58352. };
  58353. /**
  58354. * Serializes the particle system to a JSON object.
  58355. * @returns the JSON object
  58356. */
  58357. GPUParticleSystem.prototype.serialize = function () {
  58358. var serializationObject = {};
  58359. serializationObject.name = this.name;
  58360. serializationObject.id = this.id;
  58361. // Emitter
  58362. if (this.emitter.position) {
  58363. var emitterMesh = this.emitter;
  58364. serializationObject.emitterId = emitterMesh.id;
  58365. }
  58366. else {
  58367. var emitterPosition = this.emitter;
  58368. serializationObject.emitter = emitterPosition.asArray();
  58369. }
  58370. serializationObject.capacity = this.getCapacity();
  58371. if (this.particleTexture) {
  58372. serializationObject.textureName = this.particleTexture.name;
  58373. }
  58374. // Animations
  58375. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58376. // Particle system
  58377. serializationObject.activeParticleCount = this.activeParticleCount;
  58378. serializationObject.randomTextureSize = this._randomTextureSize;
  58379. serializationObject.minSize = this.minSize;
  58380. serializationObject.maxSize = this.maxSize;
  58381. serializationObject.minEmitPower = this.minEmitPower;
  58382. serializationObject.maxEmitPower = this.maxEmitPower;
  58383. serializationObject.minLifeTime = this.minLifeTime;
  58384. serializationObject.maxLifeTime = this.maxLifeTime;
  58385. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58386. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58387. serializationObject.emitRate = this.emitRate;
  58388. serializationObject.gravity = this.gravity.asArray();
  58389. serializationObject.color1 = this.color1.asArray();
  58390. serializationObject.color2 = this.color2.asArray();
  58391. serializationObject.colorDead = this.colorDead.asArray();
  58392. serializationObject.updateSpeed = this.updateSpeed;
  58393. serializationObject.targetStopDuration = this.targetStopDuration;
  58394. serializationObject.blendMode = this.blendMode;
  58395. // Emitter
  58396. if (this.particleEmitterType) {
  58397. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58398. }
  58399. return serializationObject;
  58400. };
  58401. /**
  58402. * Parses a JSON object to create a GPU particle system.
  58403. * @param parsedParticleSystem The JSON object to parse
  58404. * @param scene The scene to create the particle system in
  58405. * @param rootUrl The root url to use to load external dependencies like texture
  58406. * @returns the parsed GPU particle system
  58407. */
  58408. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58409. var name = parsedParticleSystem.name;
  58410. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58411. if (parsedParticleSystem.id) {
  58412. particleSystem.id = parsedParticleSystem.id;
  58413. }
  58414. // Texture
  58415. if (parsedParticleSystem.textureName) {
  58416. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58417. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58418. }
  58419. // Emitter
  58420. if (parsedParticleSystem.emitterId) {
  58421. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58422. }
  58423. else {
  58424. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58425. }
  58426. // Animations
  58427. if (parsedParticleSystem.animations) {
  58428. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58429. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58430. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58431. }
  58432. }
  58433. // Particle system
  58434. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58435. particleSystem.minSize = parsedParticleSystem.minSize;
  58436. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58437. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58438. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58439. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58440. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58441. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58442. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58443. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58444. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58445. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58446. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58447. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58448. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58449. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58450. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58451. // Emitter
  58452. if (parsedParticleSystem.particleEmitterType) {
  58453. var emitterType = void 0;
  58454. switch (parsedParticleSystem.particleEmitterType.type) {
  58455. case "SphereEmitter":
  58456. emitterType = new BABYLON.SphereParticleEmitter();
  58457. break;
  58458. case "SphereDirectedParticleEmitter":
  58459. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58460. break;
  58461. case "ConeEmitter":
  58462. emitterType = new BABYLON.ConeParticleEmitter();
  58463. break;
  58464. case "BoxEmitter":
  58465. default:
  58466. emitterType = new BABYLON.BoxParticleEmitter();
  58467. break;
  58468. }
  58469. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58470. particleSystem.particleEmitterType = emitterType;
  58471. }
  58472. return particleSystem;
  58473. };
  58474. return GPUParticleSystem;
  58475. }());
  58476. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58477. })(BABYLON || (BABYLON = {}));
  58478. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58479. var BABYLON;
  58480. (function (BABYLON) {
  58481. /**
  58482. * Represents one particle of a solid particle system.
  58483. */
  58484. var SolidParticle = /** @class */ (function () {
  58485. /**
  58486. * Creates a Solid Particle object.
  58487. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58488. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58489. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58490. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58491. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58492. * @param shapeId (integer) is the model shape identifier in the SPS.
  58493. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58494. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58495. */
  58496. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58497. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58498. /**
  58499. * particle global index
  58500. */
  58501. this.idx = 0;
  58502. /**
  58503. * The color of the particle
  58504. */
  58505. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58506. /**
  58507. * The world space position of the particle.
  58508. */
  58509. this.position = BABYLON.Vector3.Zero();
  58510. /**
  58511. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58512. */
  58513. this.rotation = BABYLON.Vector3.Zero();
  58514. /**
  58515. * The scaling of the particle.
  58516. */
  58517. this.scaling = BABYLON.Vector3.One();
  58518. /**
  58519. * The uvs of the particle.
  58520. */
  58521. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58522. /**
  58523. * The current speed of the particle.
  58524. */
  58525. this.velocity = BABYLON.Vector3.Zero();
  58526. /**
  58527. * The pivot point in the particle local space.
  58528. */
  58529. this.pivot = BABYLON.Vector3.Zero();
  58530. /**
  58531. * Must the particle be translated from its pivot point in its local space ?
  58532. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58533. * Default : false
  58534. */
  58535. this.translateFromPivot = false;
  58536. /**
  58537. * Is the particle active or not ?
  58538. */
  58539. this.alive = true;
  58540. /**
  58541. * Is the particle visible or not ?
  58542. */
  58543. this.isVisible = true;
  58544. /**
  58545. * Index of this particle in the global "positions" array (Internal use)
  58546. */
  58547. this._pos = 0;
  58548. /**
  58549. * Index of this particle in the global "indices" array (Internal use)
  58550. */
  58551. this._ind = 0;
  58552. /**
  58553. * ModelShape id of this particle
  58554. */
  58555. this.shapeId = 0;
  58556. /**
  58557. * Index of the particle in its shape id (Internal use)
  58558. */
  58559. this.idxInShape = 0;
  58560. /**
  58561. * Still set as invisible in order to skip useless computations (Internal use)
  58562. */
  58563. this._stillInvisible = false;
  58564. /**
  58565. * Last computed particle rotation matrix
  58566. */
  58567. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58568. /**
  58569. * Parent particle Id, if any.
  58570. * Default null.
  58571. */
  58572. this.parentId = null;
  58573. /**
  58574. * Internal global position in the SPS.
  58575. */
  58576. this._globalPosition = BABYLON.Vector3.Zero();
  58577. this.idx = particleIndex;
  58578. this._pos = positionIndex;
  58579. this._ind = indiceIndex;
  58580. this._model = model;
  58581. this.shapeId = shapeId;
  58582. this.idxInShape = idxInShape;
  58583. this._sps = sps;
  58584. if (modelBoundingInfo) {
  58585. this._modelBoundingInfo = modelBoundingInfo;
  58586. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58587. }
  58588. }
  58589. Object.defineProperty(SolidParticle.prototype, "scale", {
  58590. /**
  58591. * Legacy support, changed scale to scaling
  58592. */
  58593. get: function () {
  58594. return this.scaling;
  58595. },
  58596. /**
  58597. * Legacy support, changed scale to scaling
  58598. */
  58599. set: function (scale) {
  58600. this.scaling = scale;
  58601. },
  58602. enumerable: true,
  58603. configurable: true
  58604. });
  58605. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58606. /**
  58607. * Legacy support, changed quaternion to rotationQuaternion
  58608. */
  58609. get: function () {
  58610. return this.rotationQuaternion;
  58611. },
  58612. /**
  58613. * Legacy support, changed quaternion to rotationQuaternion
  58614. */
  58615. set: function (q) {
  58616. this.rotationQuaternion = q;
  58617. },
  58618. enumerable: true,
  58619. configurable: true
  58620. });
  58621. /**
  58622. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58623. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58624. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58625. * @returns true if it intersects
  58626. */
  58627. SolidParticle.prototype.intersectsMesh = function (target) {
  58628. if (!this._boundingInfo || !target._boundingInfo) {
  58629. return false;
  58630. }
  58631. if (this._sps._bSphereOnly) {
  58632. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58633. }
  58634. return this._boundingInfo.intersects(target._boundingInfo, false);
  58635. };
  58636. return SolidParticle;
  58637. }());
  58638. BABYLON.SolidParticle = SolidParticle;
  58639. /**
  58640. * Represents the shape of the model used by one particle of a solid particle system.
  58641. * SPS internal tool, don't use it manually.
  58642. */
  58643. var ModelShape = /** @class */ (function () {
  58644. /**
  58645. * 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.
  58646. * SPS internal tool, don't use it manually.
  58647. * @hidden
  58648. */
  58649. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58650. /**
  58651. * length of the shape in the model indices array (internal use)
  58652. */
  58653. this._indicesLength = 0;
  58654. this.shapeID = id;
  58655. this._shape = shape;
  58656. this._indicesLength = indicesLength;
  58657. this._shapeUV = shapeUV;
  58658. this._positionFunction = posFunction;
  58659. this._vertexFunction = vtxFunction;
  58660. }
  58661. return ModelShape;
  58662. }());
  58663. BABYLON.ModelShape = ModelShape;
  58664. /**
  58665. * Represents a Depth Sorted Particle in the solid particle system.
  58666. */
  58667. var DepthSortedParticle = /** @class */ (function () {
  58668. function DepthSortedParticle() {
  58669. /**
  58670. * Index of the particle in the "indices" array
  58671. */
  58672. this.ind = 0;
  58673. /**
  58674. * Length of the particle shape in the "indices" array
  58675. */
  58676. this.indicesLength = 0;
  58677. /**
  58678. * Squared distance from the particle to the camera
  58679. */
  58680. this.sqDistance = 0.0;
  58681. }
  58682. return DepthSortedParticle;
  58683. }());
  58684. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58685. })(BABYLON || (BABYLON = {}));
  58686. //# sourceMappingURL=babylon.solidParticle.js.map
  58687. var BABYLON;
  58688. (function (BABYLON) {
  58689. /**
  58690. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58691. *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.
  58692. * The SPS is also a particle system. It provides some methods to manage the particles.
  58693. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58694. *
  58695. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58696. */
  58697. var SolidParticleSystem = /** @class */ (function () {
  58698. /**
  58699. * Creates a SPS (Solid Particle System) object.
  58700. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58701. * @param scene (Scene) is the scene in which the SPS is added.
  58702. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58703. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58704. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58705. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58706. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58707. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58708. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58709. */
  58710. function SolidParticleSystem(name, scene, options) {
  58711. /**
  58712. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58713. * Example : var p = SPS.particles[i];
  58714. */
  58715. this.particles = new Array();
  58716. /**
  58717. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58718. */
  58719. this.nbParticles = 0;
  58720. /**
  58721. * If the particles must ever face the camera (default false). Useful for planar particles.
  58722. */
  58723. this.billboard = false;
  58724. /**
  58725. * Recompute normals when adding a shape
  58726. */
  58727. this.recomputeNormals = true;
  58728. /**
  58729. * This a counter ofr your own usage. It's not set by any SPS functions.
  58730. */
  58731. this.counter = 0;
  58732. /**
  58733. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58734. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58735. */
  58736. this.vars = {};
  58737. /**
  58738. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58739. */
  58740. this._bSphereOnly = false;
  58741. /**
  58742. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58743. */
  58744. this._bSphereRadiusFactor = 1.0;
  58745. this._positions = new Array();
  58746. this._indices = new Array();
  58747. this._normals = new Array();
  58748. this._colors = new Array();
  58749. this._uvs = new Array();
  58750. this._index = 0; // indices index
  58751. this._updatable = true;
  58752. this._pickable = false;
  58753. this._isVisibilityBoxLocked = false;
  58754. this._alwaysVisible = false;
  58755. this._depthSort = false;
  58756. this._shapeCounter = 0;
  58757. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58758. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58759. this._computeParticleColor = true;
  58760. this._computeParticleTexture = true;
  58761. this._computeParticleRotation = true;
  58762. this._computeParticleVertex = false;
  58763. this._computeBoundingBox = false;
  58764. this._depthSortParticles = true;
  58765. this._cam_axisZ = BABYLON.Vector3.Zero();
  58766. this._cam_axisY = BABYLON.Vector3.Zero();
  58767. this._cam_axisX = BABYLON.Vector3.Zero();
  58768. this._axisZ = BABYLON.Axis.Z;
  58769. this._camDir = BABYLON.Vector3.Zero();
  58770. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58771. this._rotMatrix = new BABYLON.Matrix();
  58772. this._invertMatrix = new BABYLON.Matrix();
  58773. this._rotated = BABYLON.Vector3.Zero();
  58774. this._quaternion = new BABYLON.Quaternion();
  58775. this._vertex = BABYLON.Vector3.Zero();
  58776. this._normal = BABYLON.Vector3.Zero();
  58777. this._yaw = 0.0;
  58778. this._pitch = 0.0;
  58779. this._roll = 0.0;
  58780. this._halfroll = 0.0;
  58781. this._halfpitch = 0.0;
  58782. this._halfyaw = 0.0;
  58783. this._sinRoll = 0.0;
  58784. this._cosRoll = 0.0;
  58785. this._sinPitch = 0.0;
  58786. this._cosPitch = 0.0;
  58787. this._sinYaw = 0.0;
  58788. this._cosYaw = 0.0;
  58789. this._mustUnrotateFixedNormals = false;
  58790. this._minimum = BABYLON.Vector3.Zero();
  58791. this._maximum = BABYLON.Vector3.Zero();
  58792. this._minBbox = BABYLON.Vector3.Zero();
  58793. this._maxBbox = BABYLON.Vector3.Zero();
  58794. this._particlesIntersect = false;
  58795. this._depthSortFunction = function (p1, p2) {
  58796. return (p2.sqDistance - p1.sqDistance);
  58797. };
  58798. this._needs32Bits = false;
  58799. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58800. this._scaledPivot = BABYLON.Vector3.Zero();
  58801. this._particleHasParent = false;
  58802. this.name = name;
  58803. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58804. this._camera = scene.activeCamera;
  58805. this._pickable = options ? options.isPickable : false;
  58806. this._depthSort = options ? options.enableDepthSort : false;
  58807. this._particlesIntersect = options ? options.particleIntersection : false;
  58808. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58809. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58810. if (options && options.updatable !== undefined) {
  58811. this._updatable = options.updatable;
  58812. }
  58813. else {
  58814. this._updatable = true;
  58815. }
  58816. if (this._pickable) {
  58817. this.pickedParticles = [];
  58818. }
  58819. if (this._depthSort) {
  58820. this.depthSortedParticles = [];
  58821. }
  58822. }
  58823. /**
  58824. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58825. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58826. * @returns the created mesh
  58827. */
  58828. SolidParticleSystem.prototype.buildMesh = function () {
  58829. if (this.nbParticles === 0) {
  58830. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58831. this.addShape(triangle, 1);
  58832. triangle.dispose();
  58833. }
  58834. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58835. this._positions32 = new Float32Array(this._positions);
  58836. this._uvs32 = new Float32Array(this._uvs);
  58837. this._colors32 = new Float32Array(this._colors);
  58838. if (this.recomputeNormals) {
  58839. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58840. }
  58841. this._normals32 = new Float32Array(this._normals);
  58842. this._fixedNormal32 = new Float32Array(this._normals);
  58843. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58844. this._unrotateFixedNormals();
  58845. }
  58846. var vertexData = new BABYLON.VertexData();
  58847. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58848. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58849. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58850. if (this._uvs32.length > 0) {
  58851. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58852. }
  58853. if (this._colors32.length > 0) {
  58854. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58855. }
  58856. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58857. vertexData.applyToMesh(mesh, this._updatable);
  58858. this.mesh = mesh;
  58859. this.mesh.isPickable = this._pickable;
  58860. // free memory
  58861. if (!this._depthSort) {
  58862. this._indices = null;
  58863. }
  58864. this._positions = null;
  58865. this._normals = null;
  58866. this._uvs = null;
  58867. this._colors = null;
  58868. if (!this._updatable) {
  58869. this.particles.length = 0;
  58870. }
  58871. return mesh;
  58872. };
  58873. /**
  58874. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58875. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58876. * Thus the particles generated from `digest()` have their property `position` set yet.
  58877. * @param mesh ( Mesh ) is the mesh to be digested
  58878. * @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
  58879. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58880. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58881. * @returns the current SPS
  58882. */
  58883. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58884. var size = (options && options.facetNb) || 1;
  58885. var number = (options && options.number) || 0;
  58886. var delta = (options && options.delta) || 0;
  58887. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58888. var meshInd = mesh.getIndices();
  58889. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58890. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58891. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58892. var f = 0; // facet counter
  58893. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58894. // compute size from number
  58895. if (number) {
  58896. number = (number > totalFacets) ? totalFacets : number;
  58897. size = Math.round(totalFacets / number);
  58898. delta = 0;
  58899. }
  58900. else {
  58901. size = (size > totalFacets) ? totalFacets : size;
  58902. }
  58903. var facetPos = []; // submesh positions
  58904. var facetInd = []; // submesh indices
  58905. var facetUV = []; // submesh UV
  58906. var facetCol = []; // submesh colors
  58907. var barycenter = BABYLON.Vector3.Zero();
  58908. var sizeO = size;
  58909. while (f < totalFacets) {
  58910. size = sizeO + Math.floor((1 + delta) * Math.random());
  58911. if (f > totalFacets - size) {
  58912. size = totalFacets - f;
  58913. }
  58914. // reset temp arrays
  58915. facetPos.length = 0;
  58916. facetInd.length = 0;
  58917. facetUV.length = 0;
  58918. facetCol.length = 0;
  58919. // iterate over "size" facets
  58920. var fi = 0;
  58921. for (var j = f * 3; j < (f + size) * 3; j++) {
  58922. facetInd.push(fi);
  58923. var i = meshInd[j];
  58924. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58925. if (meshUV) {
  58926. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58927. }
  58928. if (meshCol) {
  58929. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58930. }
  58931. fi++;
  58932. }
  58933. // create a model shape for each single particle
  58934. var idx = this.nbParticles;
  58935. var shape = this._posToShape(facetPos);
  58936. var shapeUV = this._uvsToShapeUV(facetUV);
  58937. // compute the barycenter of the shape
  58938. var v;
  58939. for (v = 0; v < shape.length; v++) {
  58940. barycenter.addInPlace(shape[v]);
  58941. }
  58942. barycenter.scaleInPlace(1 / shape.length);
  58943. // shift the shape from its barycenter to the origin
  58944. for (v = 0; v < shape.length; v++) {
  58945. shape[v].subtractInPlace(barycenter);
  58946. }
  58947. var bInfo;
  58948. if (this._particlesIntersect) {
  58949. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58950. }
  58951. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58952. // add the particle in the SPS
  58953. var currentPos = this._positions.length;
  58954. var currentInd = this._indices.length;
  58955. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58956. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58957. // initialize the particle position
  58958. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58959. this._index += shape.length;
  58960. idx++;
  58961. this.nbParticles++;
  58962. this._shapeCounter++;
  58963. f += size;
  58964. }
  58965. return this;
  58966. };
  58967. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58968. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58969. var index = 0;
  58970. var idx = 0;
  58971. for (var p = 0; p < this.particles.length; p++) {
  58972. this._particle = this.particles[p];
  58973. this._shape = this._particle._model._shape;
  58974. if (this._particle.rotationQuaternion) {
  58975. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58976. }
  58977. else {
  58978. this._yaw = this._particle.rotation.y;
  58979. this._pitch = this._particle.rotation.x;
  58980. this._roll = this._particle.rotation.z;
  58981. this._quaternionRotationYPR();
  58982. }
  58983. this._quaternionToRotationMatrix();
  58984. this._rotMatrix.invertToRef(this._invertMatrix);
  58985. for (var pt = 0; pt < this._shape.length; pt++) {
  58986. idx = index + pt * 3;
  58987. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58988. this._fixedNormal32[idx] = this._normal.x;
  58989. this._fixedNormal32[idx + 1] = this._normal.y;
  58990. this._fixedNormal32[idx + 2] = this._normal.z;
  58991. }
  58992. index = idx + 3;
  58993. }
  58994. };
  58995. //reset copy
  58996. SolidParticleSystem.prototype._resetCopy = function () {
  58997. this._copy.position.x = 0;
  58998. this._copy.position.y = 0;
  58999. this._copy.position.z = 0;
  59000. this._copy.rotation.x = 0;
  59001. this._copy.rotation.y = 0;
  59002. this._copy.rotation.z = 0;
  59003. this._copy.rotationQuaternion = null;
  59004. this._copy.scaling.x = 1.0;
  59005. this._copy.scaling.y = 1.0;
  59006. this._copy.scaling.z = 1.0;
  59007. this._copy.uvs.x = 0;
  59008. this._copy.uvs.y = 0;
  59009. this._copy.uvs.z = 1.0;
  59010. this._copy.uvs.w = 1.0;
  59011. this._copy.color = null;
  59012. this._copy.translateFromPivot = false;
  59013. };
  59014. // _meshBuilder : inserts the shape model in the global SPS mesh
  59015. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  59016. var i;
  59017. var u = 0;
  59018. var c = 0;
  59019. var n = 0;
  59020. this._resetCopy();
  59021. if (options && options.positionFunction) { // call to custom positionFunction
  59022. options.positionFunction(this._copy, idx, idxInShape);
  59023. this._mustUnrotateFixedNormals = true;
  59024. }
  59025. if (this._copy.rotationQuaternion) {
  59026. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59027. }
  59028. else {
  59029. this._yaw = this._copy.rotation.y;
  59030. this._pitch = this._copy.rotation.x;
  59031. this._roll = this._copy.rotation.z;
  59032. this._quaternionRotationYPR();
  59033. }
  59034. this._quaternionToRotationMatrix();
  59035. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  59036. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  59037. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  59038. if (this._copy.translateFromPivot) {
  59039. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59040. }
  59041. else {
  59042. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59043. }
  59044. for (i = 0; i < shape.length; i++) {
  59045. this._vertex.x = shape[i].x;
  59046. this._vertex.y = shape[i].y;
  59047. this._vertex.z = shape[i].z;
  59048. if (options && options.vertexFunction) {
  59049. options.vertexFunction(this._copy, this._vertex, i);
  59050. }
  59051. this._vertex.x *= this._copy.scaling.x;
  59052. this._vertex.y *= this._copy.scaling.y;
  59053. this._vertex.z *= this._copy.scaling.z;
  59054. this._vertex.x -= this._scaledPivot.x;
  59055. this._vertex.y -= this._scaledPivot.y;
  59056. this._vertex.z -= this._scaledPivot.z;
  59057. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59058. this._rotated.addInPlace(this._pivotBackTranslation);
  59059. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  59060. if (meshUV) {
  59061. 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);
  59062. u += 2;
  59063. }
  59064. if (this._copy.color) {
  59065. this._color = this._copy.color;
  59066. }
  59067. else if (meshCol && meshCol[c] !== undefined) {
  59068. this._color.r = meshCol[c];
  59069. this._color.g = meshCol[c + 1];
  59070. this._color.b = meshCol[c + 2];
  59071. this._color.a = meshCol[c + 3];
  59072. }
  59073. else {
  59074. this._color.r = 1.0;
  59075. this._color.g = 1.0;
  59076. this._color.b = 1.0;
  59077. this._color.a = 1.0;
  59078. }
  59079. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59080. c += 4;
  59081. if (!this.recomputeNormals && meshNor) {
  59082. this._normal.x = meshNor[n];
  59083. this._normal.y = meshNor[n + 1];
  59084. this._normal.z = meshNor[n + 2];
  59085. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59086. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59087. n += 3;
  59088. }
  59089. }
  59090. for (i = 0; i < meshInd.length; i++) {
  59091. var current_ind = p + meshInd[i];
  59092. indices.push(current_ind);
  59093. if (current_ind > 65535) {
  59094. this._needs32Bits = true;
  59095. }
  59096. }
  59097. if (this._pickable) {
  59098. var nbfaces = meshInd.length / 3;
  59099. for (i = 0; i < nbfaces; i++) {
  59100. this.pickedParticles.push({ idx: idx, faceId: i });
  59101. }
  59102. }
  59103. if (this._depthSort) {
  59104. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59105. }
  59106. return this._copy;
  59107. };
  59108. // returns a shape array from positions array
  59109. SolidParticleSystem.prototype._posToShape = function (positions) {
  59110. var shape = [];
  59111. for (var i = 0; i < positions.length; i += 3) {
  59112. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59113. }
  59114. return shape;
  59115. };
  59116. // returns a shapeUV array from a Vector4 uvs
  59117. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59118. var shapeUV = [];
  59119. if (uvs) {
  59120. for (var i = 0; i < uvs.length; i++)
  59121. shapeUV.push(uvs[i]);
  59122. }
  59123. return shapeUV;
  59124. };
  59125. // adds a new particle object in the particles array
  59126. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59127. if (bInfo === void 0) { bInfo = null; }
  59128. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59129. this.particles.push(sp);
  59130. return sp;
  59131. };
  59132. /**
  59133. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59134. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59135. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59136. * @param nb (positive integer) the number of particles to be created from this model
  59137. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59138. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59139. * @returns the number of shapes in the system
  59140. */
  59141. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59142. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59143. var meshInd = mesh.getIndices();
  59144. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59145. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59146. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59147. var bbInfo;
  59148. if (this._particlesIntersect) {
  59149. bbInfo = mesh.getBoundingInfo();
  59150. }
  59151. var shape = this._posToShape(meshPos);
  59152. var shapeUV = this._uvsToShapeUV(meshUV);
  59153. var posfunc = options ? options.positionFunction : null;
  59154. var vtxfunc = options ? options.vertexFunction : null;
  59155. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59156. // particles
  59157. var sp;
  59158. var currentCopy;
  59159. var idx = this.nbParticles;
  59160. for (var i = 0; i < nb; i++) {
  59161. var currentPos = this._positions.length;
  59162. var currentInd = this._indices.length;
  59163. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59164. if (this._updatable) {
  59165. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59166. sp.position.copyFrom(currentCopy.position);
  59167. sp.rotation.copyFrom(currentCopy.rotation);
  59168. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59169. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59170. }
  59171. if (currentCopy.color && sp.color) {
  59172. sp.color.copyFrom(currentCopy.color);
  59173. }
  59174. sp.scaling.copyFrom(currentCopy.scaling);
  59175. sp.uvs.copyFrom(currentCopy.uvs);
  59176. }
  59177. this._index += shape.length;
  59178. idx++;
  59179. }
  59180. this.nbParticles += nb;
  59181. this._shapeCounter++;
  59182. return this._shapeCounter - 1;
  59183. };
  59184. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59185. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59186. this._resetCopy();
  59187. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59188. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59189. }
  59190. if (this._copy.rotationQuaternion) {
  59191. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59192. }
  59193. else {
  59194. this._yaw = this._copy.rotation.y;
  59195. this._pitch = this._copy.rotation.x;
  59196. this._roll = this._copy.rotation.z;
  59197. this._quaternionRotationYPR();
  59198. }
  59199. this._quaternionToRotationMatrix();
  59200. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59201. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59202. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59203. if (this._copy.translateFromPivot) {
  59204. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59205. }
  59206. else {
  59207. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59208. }
  59209. this._shape = particle._model._shape;
  59210. for (var pt = 0; pt < this._shape.length; pt++) {
  59211. this._vertex.x = this._shape[pt].x;
  59212. this._vertex.y = this._shape[pt].y;
  59213. this._vertex.z = this._shape[pt].z;
  59214. if (particle._model._vertexFunction) {
  59215. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59216. }
  59217. this._vertex.x *= this._copy.scaling.x;
  59218. this._vertex.y *= this._copy.scaling.y;
  59219. this._vertex.z *= this._copy.scaling.z;
  59220. this._vertex.x -= this._scaledPivot.x;
  59221. this._vertex.y -= this._scaledPivot.y;
  59222. this._vertex.z -= this._scaledPivot.z;
  59223. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59224. this._rotated.addInPlace(this._pivotBackTranslation);
  59225. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59226. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59227. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59228. }
  59229. particle.position.x = 0.0;
  59230. particle.position.y = 0.0;
  59231. particle.position.z = 0.0;
  59232. particle.rotation.x = 0.0;
  59233. particle.rotation.y = 0.0;
  59234. particle.rotation.z = 0.0;
  59235. particle.rotationQuaternion = null;
  59236. particle.scaling.x = 1.0;
  59237. particle.scaling.y = 1.0;
  59238. particle.scaling.z = 1.0;
  59239. particle.uvs.x = 0.0;
  59240. particle.uvs.y = 0.0;
  59241. particle.uvs.z = 1.0;
  59242. particle.uvs.w = 1.0;
  59243. particle.pivot.x = 0.0;
  59244. particle.pivot.y = 0.0;
  59245. particle.pivot.z = 0.0;
  59246. particle.translateFromPivot = false;
  59247. particle.parentId = null;
  59248. };
  59249. /**
  59250. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59251. * @returns the SPS.
  59252. */
  59253. SolidParticleSystem.prototype.rebuildMesh = function () {
  59254. for (var p = 0; p < this.particles.length; p++) {
  59255. this._rebuildParticle(this.particles[p]);
  59256. }
  59257. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59258. return this;
  59259. };
  59260. /**
  59261. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59262. * This method calls `updateParticle()` for each particle of the SPS.
  59263. * For an animated SPS, it is usually called within the render loop.
  59264. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59265. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59266. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59267. * @returns the SPS.
  59268. */
  59269. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59270. if (start === void 0) { start = 0; }
  59271. if (end === void 0) { end = this.nbParticles - 1; }
  59272. if (update === void 0) { update = true; }
  59273. if (!this._updatable) {
  59274. return this;
  59275. }
  59276. // custom beforeUpdate
  59277. this.beforeUpdateParticles(start, end, update);
  59278. this._cam_axisX.x = 1.0;
  59279. this._cam_axisX.y = 0.0;
  59280. this._cam_axisX.z = 0.0;
  59281. this._cam_axisY.x = 0.0;
  59282. this._cam_axisY.y = 1.0;
  59283. this._cam_axisY.z = 0.0;
  59284. this._cam_axisZ.x = 0.0;
  59285. this._cam_axisZ.y = 0.0;
  59286. this._cam_axisZ.z = 1.0;
  59287. // cases when the World Matrix is to be computed first
  59288. if (this.billboard || this._depthSort) {
  59289. this.mesh.computeWorldMatrix(true);
  59290. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59291. }
  59292. // if the particles will always face the camera
  59293. if (this.billboard) {
  59294. // compute the camera position and un-rotate it by the current mesh rotation
  59295. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59296. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59297. this._cam_axisZ.normalize();
  59298. // same for camera up vector extracted from the cam view matrix
  59299. var view = this._camera.getViewMatrix(true);
  59300. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59301. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59302. this._cam_axisY.normalize();
  59303. this._cam_axisX.normalize();
  59304. }
  59305. // if depthSort, compute the camera global position in the mesh local system
  59306. if (this._depthSort) {
  59307. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59308. }
  59309. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59310. var idx = 0; // current position index in the global array positions32
  59311. var index = 0; // position start index in the global array positions32 of the current particle
  59312. var colidx = 0; // current color index in the global array colors32
  59313. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59314. var uvidx = 0; // current uv index in the global array uvs32
  59315. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59316. var pt = 0; // current index in the particle model shape
  59317. if (this.mesh.isFacetDataEnabled) {
  59318. this._computeBoundingBox = true;
  59319. }
  59320. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59321. if (this._computeBoundingBox) {
  59322. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59323. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59324. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59325. }
  59326. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59327. if (this.mesh._boundingInfo) {
  59328. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59329. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59330. }
  59331. }
  59332. }
  59333. // particle loop
  59334. index = this.particles[start]._pos;
  59335. var vpos = (index / 3) | 0;
  59336. colorIndex = vpos * 4;
  59337. uvIndex = vpos * 2;
  59338. for (var p = start; p <= end; p++) {
  59339. this._particle = this.particles[p];
  59340. this._shape = this._particle._model._shape;
  59341. this._shapeUV = this._particle._model._shapeUV;
  59342. // call to custom user function to update the particle properties
  59343. this.updateParticle(this._particle);
  59344. // camera-particle distance for depth sorting
  59345. if (this._depthSort && this._depthSortParticles) {
  59346. var dsp = this.depthSortedParticles[p];
  59347. dsp.ind = this._particle._ind;
  59348. dsp.indicesLength = this._particle._model._indicesLength;
  59349. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59350. }
  59351. // skip the computations for inactive or already invisible particles
  59352. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59353. // increment indexes for the next particle
  59354. pt = this._shape.length;
  59355. index += pt * 3;
  59356. colorIndex += pt * 4;
  59357. uvIndex += pt * 2;
  59358. continue;
  59359. }
  59360. if (this._particle.isVisible) {
  59361. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59362. this._particleHasParent = (this._particle.parentId !== null);
  59363. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59364. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59365. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59366. // particle rotation matrix
  59367. if (this.billboard) {
  59368. this._particle.rotation.x = 0.0;
  59369. this._particle.rotation.y = 0.0;
  59370. }
  59371. if (this._computeParticleRotation || this.billboard) {
  59372. if (this._particle.rotationQuaternion) {
  59373. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59374. }
  59375. else {
  59376. this._yaw = this._particle.rotation.y;
  59377. this._pitch = this._particle.rotation.x;
  59378. this._roll = this._particle.rotation.z;
  59379. this._quaternionRotationYPR();
  59380. }
  59381. this._quaternionToRotationMatrix();
  59382. }
  59383. if (this._particleHasParent) {
  59384. this._parent = this.particles[this._particle.parentId];
  59385. 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];
  59386. 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];
  59387. 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];
  59388. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59389. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59390. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59391. if (this._computeParticleRotation || this.billboard) {
  59392. 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];
  59393. 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];
  59394. 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];
  59395. 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];
  59396. 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];
  59397. 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];
  59398. 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];
  59399. 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];
  59400. 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];
  59401. }
  59402. }
  59403. else {
  59404. this._particle._globalPosition.x = this._particle.position.x;
  59405. this._particle._globalPosition.y = this._particle.position.y;
  59406. this._particle._globalPosition.z = this._particle.position.z;
  59407. if (this._computeParticleRotation || this.billboard) {
  59408. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59409. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59410. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59411. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59412. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59413. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59414. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59415. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59416. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59417. }
  59418. }
  59419. if (this._particle.translateFromPivot) {
  59420. this._pivotBackTranslation.x = 0.0;
  59421. this._pivotBackTranslation.y = 0.0;
  59422. this._pivotBackTranslation.z = 0.0;
  59423. }
  59424. else {
  59425. this._pivotBackTranslation.x = this._scaledPivot.x;
  59426. this._pivotBackTranslation.y = this._scaledPivot.y;
  59427. this._pivotBackTranslation.z = this._scaledPivot.z;
  59428. }
  59429. // particle vertex loop
  59430. for (pt = 0; pt < this._shape.length; pt++) {
  59431. idx = index + pt * 3;
  59432. colidx = colorIndex + pt * 4;
  59433. uvidx = uvIndex + pt * 2;
  59434. this._vertex.x = this._shape[pt].x;
  59435. this._vertex.y = this._shape[pt].y;
  59436. this._vertex.z = this._shape[pt].z;
  59437. if (this._computeParticleVertex) {
  59438. this.updateParticleVertex(this._particle, this._vertex, pt);
  59439. }
  59440. // positions
  59441. this._vertex.x *= this._particle.scaling.x;
  59442. this._vertex.y *= this._particle.scaling.y;
  59443. this._vertex.z *= this._particle.scaling.z;
  59444. this._vertex.x -= this._scaledPivot.x;
  59445. this._vertex.y -= this._scaledPivot.y;
  59446. this._vertex.z -= this._scaledPivot.z;
  59447. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59448. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59449. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59450. this._rotated.x += this._pivotBackTranslation.x;
  59451. this._rotated.y += this._pivotBackTranslation.y;
  59452. this._rotated.z += this._pivotBackTranslation.z;
  59453. 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;
  59454. 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;
  59455. 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;
  59456. if (this._computeBoundingBox) {
  59457. if (this._positions32[idx] < this._minimum.x) {
  59458. this._minimum.x = this._positions32[idx];
  59459. }
  59460. if (this._positions32[idx] > this._maximum.x) {
  59461. this._maximum.x = this._positions32[idx];
  59462. }
  59463. if (this._positions32[idx + 1] < this._minimum.y) {
  59464. this._minimum.y = this._positions32[idx + 1];
  59465. }
  59466. if (this._positions32[idx + 1] > this._maximum.y) {
  59467. this._maximum.y = this._positions32[idx + 1];
  59468. }
  59469. if (this._positions32[idx + 2] < this._minimum.z) {
  59470. this._minimum.z = this._positions32[idx + 2];
  59471. }
  59472. if (this._positions32[idx + 2] > this._maximum.z) {
  59473. this._maximum.z = this._positions32[idx + 2];
  59474. }
  59475. }
  59476. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59477. if (!this._computeParticleVertex) {
  59478. this._normal.x = this._fixedNormal32[idx];
  59479. this._normal.y = this._fixedNormal32[idx + 1];
  59480. this._normal.z = this._fixedNormal32[idx + 2];
  59481. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59482. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59483. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59484. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59485. 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;
  59486. 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;
  59487. }
  59488. if (this._computeParticleColor && this._particle.color) {
  59489. this._colors32[colidx] = this._particle.color.r;
  59490. this._colors32[colidx + 1] = this._particle.color.g;
  59491. this._colors32[colidx + 2] = this._particle.color.b;
  59492. this._colors32[colidx + 3] = this._particle.color.a;
  59493. }
  59494. if (this._computeParticleTexture) {
  59495. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59496. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59497. }
  59498. }
  59499. }
  59500. // particle just set invisible : scaled to zero and positioned at the origin
  59501. else {
  59502. this._particle._stillInvisible = true; // mark the particle as invisible
  59503. for (pt = 0; pt < this._shape.length; pt++) {
  59504. idx = index + pt * 3;
  59505. colidx = colorIndex + pt * 4;
  59506. uvidx = uvIndex + pt * 2;
  59507. this._positions32[idx] = 0.0;
  59508. this._positions32[idx + 1] = 0.0;
  59509. this._positions32[idx + 2] = 0.0;
  59510. this._normals32[idx] = 0.0;
  59511. this._normals32[idx + 1] = 0.0;
  59512. this._normals32[idx + 2] = 0.0;
  59513. if (this._computeParticleColor && this._particle.color) {
  59514. this._colors32[colidx] = this._particle.color.r;
  59515. this._colors32[colidx + 1] = this._particle.color.g;
  59516. this._colors32[colidx + 2] = this._particle.color.b;
  59517. this._colors32[colidx + 3] = this._particle.color.a;
  59518. }
  59519. if (this._computeParticleTexture) {
  59520. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59521. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59522. }
  59523. }
  59524. }
  59525. // if the particle intersections must be computed : update the bbInfo
  59526. if (this._particlesIntersect) {
  59527. var bInfo = this._particle._boundingInfo;
  59528. var bBox = bInfo.boundingBox;
  59529. var bSphere = bInfo.boundingSphere;
  59530. if (!this._bSphereOnly) {
  59531. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59532. for (var b = 0; b < bBox.vectors.length; b++) {
  59533. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59534. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59535. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59536. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59537. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59538. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59539. 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;
  59540. 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;
  59541. 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;
  59542. }
  59543. bBox._update(this.mesh._worldMatrix);
  59544. }
  59545. // place and scale the particle bouding sphere in the SPS local system, then update it
  59546. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59547. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59548. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59549. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59550. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59551. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59552. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59553. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59554. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59555. 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));
  59556. bSphere._update(this.mesh._worldMatrix);
  59557. }
  59558. // increment indexes for the next particle
  59559. index = idx + 3;
  59560. colorIndex = colidx + 4;
  59561. uvIndex = uvidx + 2;
  59562. }
  59563. // if the VBO must be updated
  59564. if (update) {
  59565. if (this._computeParticleColor) {
  59566. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59567. }
  59568. if (this._computeParticleTexture) {
  59569. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59570. }
  59571. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59572. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59573. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59574. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59575. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59576. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59577. for (var i = 0; i < this._normals32.length; i++) {
  59578. this._fixedNormal32[i] = this._normals32[i];
  59579. }
  59580. }
  59581. if (!this.mesh.areNormalsFrozen) {
  59582. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59583. }
  59584. }
  59585. if (this._depthSort && this._depthSortParticles) {
  59586. this.depthSortedParticles.sort(this._depthSortFunction);
  59587. var dspl = this.depthSortedParticles.length;
  59588. var sorted = 0;
  59589. var lind = 0;
  59590. var sind = 0;
  59591. var sid = 0;
  59592. for (sorted = 0; sorted < dspl; sorted++) {
  59593. lind = this.depthSortedParticles[sorted].indicesLength;
  59594. sind = this.depthSortedParticles[sorted].ind;
  59595. for (var i = 0; i < lind; i++) {
  59596. this._indices32[sid] = this._indices[sind + i];
  59597. sid++;
  59598. }
  59599. }
  59600. this.mesh.updateIndices(this._indices32);
  59601. }
  59602. }
  59603. if (this._computeBoundingBox) {
  59604. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59605. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59606. }
  59607. this.afterUpdateParticles(start, end, update);
  59608. return this;
  59609. };
  59610. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59611. this._halfroll = this._roll * 0.5;
  59612. this._halfpitch = this._pitch * 0.5;
  59613. this._halfyaw = this._yaw * 0.5;
  59614. this._sinRoll = Math.sin(this._halfroll);
  59615. this._cosRoll = Math.cos(this._halfroll);
  59616. this._sinPitch = Math.sin(this._halfpitch);
  59617. this._cosPitch = Math.cos(this._halfpitch);
  59618. this._sinYaw = Math.sin(this._halfyaw);
  59619. this._cosYaw = Math.cos(this._halfyaw);
  59620. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59621. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59622. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59623. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59624. };
  59625. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59626. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59627. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59628. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59629. this._rotMatrix.m[3] = 0;
  59630. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59631. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59632. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59633. this._rotMatrix.m[7] = 0;
  59634. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59635. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59636. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59637. this._rotMatrix.m[11] = 0;
  59638. this._rotMatrix.m[12] = 0;
  59639. this._rotMatrix.m[13] = 0;
  59640. this._rotMatrix.m[14] = 0;
  59641. this._rotMatrix.m[15] = 1.0;
  59642. };
  59643. /**
  59644. * Disposes the SPS.
  59645. */
  59646. SolidParticleSystem.prototype.dispose = function () {
  59647. this.mesh.dispose();
  59648. this.vars = null;
  59649. // drop references to internal big arrays for the GC
  59650. this._positions = null;
  59651. this._indices = null;
  59652. this._normals = null;
  59653. this._uvs = null;
  59654. this._colors = null;
  59655. this._indices32 = null;
  59656. this._positions32 = null;
  59657. this._normals32 = null;
  59658. this._fixedNormal32 = null;
  59659. this._uvs32 = null;
  59660. this._colors32 = null;
  59661. this.pickedParticles = null;
  59662. };
  59663. /**
  59664. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59666. * @returns the SPS.
  59667. */
  59668. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59669. if (!this._isVisibilityBoxLocked) {
  59670. this.mesh.refreshBoundingInfo();
  59671. }
  59672. return this;
  59673. };
  59674. /**
  59675. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59676. * @param size the size (float) of the visibility box
  59677. * note : this doesn't lock the SPS mesh bounding box.
  59678. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59679. */
  59680. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59681. var vis = size / 2;
  59682. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59683. };
  59684. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59685. /**
  59686. * Gets whether the SPS as always visible or not
  59687. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59688. */
  59689. get: function () {
  59690. return this._alwaysVisible;
  59691. },
  59692. /**
  59693. * Sets the SPS as always visible or not
  59694. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59695. */
  59696. set: function (val) {
  59697. this._alwaysVisible = val;
  59698. this.mesh.alwaysSelectAsActiveMesh = val;
  59699. },
  59700. enumerable: true,
  59701. configurable: true
  59702. });
  59703. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59704. /**
  59705. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59706. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59707. */
  59708. get: function () {
  59709. return this._isVisibilityBoxLocked;
  59710. },
  59711. /**
  59712. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59713. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59714. */
  59715. set: function (val) {
  59716. this._isVisibilityBoxLocked = val;
  59717. var boundingInfo = this.mesh.getBoundingInfo();
  59718. boundingInfo.isLocked = val;
  59719. },
  59720. enumerable: true,
  59721. configurable: true
  59722. });
  59723. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59724. /**
  59725. * Gets if `setParticles()` computes the particle rotations or not.
  59726. * Default value : true. The SPS is faster when it's set to false.
  59727. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59728. */
  59729. get: function () {
  59730. return this._computeParticleRotation;
  59731. },
  59732. /**
  59733. * Tells to `setParticles()` to compute the particle rotations or not.
  59734. * Default value : true. The SPS is faster when it's set to false.
  59735. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59736. */
  59737. set: function (val) {
  59738. this._computeParticleRotation = val;
  59739. },
  59740. enumerable: true,
  59741. configurable: true
  59742. });
  59743. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59744. /**
  59745. * Gets if `setParticles()` computes the particle colors or not.
  59746. * Default value : true. The SPS is faster when it's set to false.
  59747. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59748. */
  59749. get: function () {
  59750. return this._computeParticleColor;
  59751. },
  59752. /**
  59753. * Tells to `setParticles()` to compute the particle colors or not.
  59754. * Default value : true. The SPS is faster when it's set to false.
  59755. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59756. */
  59757. set: function (val) {
  59758. this._computeParticleColor = val;
  59759. },
  59760. enumerable: true,
  59761. configurable: true
  59762. });
  59763. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59764. /**
  59765. * Gets if `setParticles()` computes the particle textures or not.
  59766. * Default value : true. The SPS is faster when it's set to false.
  59767. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59768. */
  59769. get: function () {
  59770. return this._computeParticleTexture;
  59771. },
  59772. set: function (val) {
  59773. this._computeParticleTexture = val;
  59774. },
  59775. enumerable: true,
  59776. configurable: true
  59777. });
  59778. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59779. /**
  59780. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59781. * Default value : false. The SPS is faster when it's set to false.
  59782. * Note : the particle custom vertex positions aren't stored values.
  59783. */
  59784. get: function () {
  59785. return this._computeParticleVertex;
  59786. },
  59787. /**
  59788. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59789. * Default value : false. The SPS is faster when it's set to false.
  59790. * Note : the particle custom vertex positions aren't stored values.
  59791. */
  59792. set: function (val) {
  59793. this._computeParticleVertex = val;
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59799. /**
  59800. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59801. */
  59802. get: function () {
  59803. return this._computeBoundingBox;
  59804. },
  59805. /**
  59806. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59807. */
  59808. set: function (val) {
  59809. this._computeBoundingBox = val;
  59810. },
  59811. enumerable: true,
  59812. configurable: true
  59813. });
  59814. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59815. /**
  59816. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59817. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59818. * Default : `true`
  59819. */
  59820. get: function () {
  59821. return this._depthSortParticles;
  59822. },
  59823. /**
  59824. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59825. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59826. * Default : `true`
  59827. */
  59828. set: function (val) {
  59829. this._depthSortParticles = val;
  59830. },
  59831. enumerable: true,
  59832. configurable: true
  59833. });
  59834. // =======================================================================
  59835. // Particle behavior logic
  59836. // these following methods may be overwritten by the user to fit his needs
  59837. /**
  59838. * This function does nothing. It may be overwritten to set all the particle first values.
  59839. * The SPS doesn't call this function, you may have to call it by your own.
  59840. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59841. */
  59842. SolidParticleSystem.prototype.initParticles = function () {
  59843. };
  59844. /**
  59845. * This function does nothing. It may be overwritten to recycle a particle.
  59846. * The SPS doesn't call this function, you may have to call it by your own.
  59847. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59848. * @param particle The particle to recycle
  59849. * @returns the recycled particle
  59850. */
  59851. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59852. return particle;
  59853. };
  59854. /**
  59855. * Updates a particle : this function should be overwritten by the user.
  59856. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59857. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59858. * @example : just set a particle position or velocity and recycle conditions
  59859. * @param particle The particle to update
  59860. * @returns the updated particle
  59861. */
  59862. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59863. return particle;
  59864. };
  59865. /**
  59866. * Updates a vertex of a particle : it can be overwritten by the user.
  59867. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59868. * @param particle the current particle
  59869. * @param vertex the current index of the current particle
  59870. * @param pt the index of the current vertex in the particle shape
  59871. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59872. * @example : just set a vertex particle position
  59873. * @returns the updated vertex
  59874. */
  59875. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59876. return vertex;
  59877. };
  59878. /**
  59879. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59880. * This does nothing and may be overwritten by the user.
  59881. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59882. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59883. * @param update the boolean update value actually passed to setParticles()
  59884. */
  59885. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59886. };
  59887. /**
  59888. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59889. * This will be passed three parameters.
  59890. * This does nothing and may be overwritten by the user.
  59891. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59892. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59893. * @param update the boolean update value actually passed to setParticles()
  59894. */
  59895. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59896. };
  59897. return SolidParticleSystem;
  59898. }());
  59899. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59900. })(BABYLON || (BABYLON = {}));
  59901. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59902. var BABYLON;
  59903. (function (BABYLON) {
  59904. var ShaderMaterial = /** @class */ (function (_super) {
  59905. __extends(ShaderMaterial, _super);
  59906. function ShaderMaterial(name, scene, shaderPath, options) {
  59907. var _this = _super.call(this, name, scene) || this;
  59908. _this._textures = {};
  59909. _this._textureArrays = {};
  59910. _this._floats = {};
  59911. _this._ints = {};
  59912. _this._floatsArrays = {};
  59913. _this._colors3 = {};
  59914. _this._colors3Arrays = {};
  59915. _this._colors4 = {};
  59916. _this._vectors2 = {};
  59917. _this._vectors3 = {};
  59918. _this._vectors4 = {};
  59919. _this._matrices = {};
  59920. _this._matrices3x3 = {};
  59921. _this._matrices2x2 = {};
  59922. _this._vectors2Arrays = {};
  59923. _this._vectors3Arrays = {};
  59924. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59925. _this._shaderPath = shaderPath;
  59926. options.needAlphaBlending = options.needAlphaBlending || false;
  59927. options.needAlphaTesting = options.needAlphaTesting || false;
  59928. options.attributes = options.attributes || ["position", "normal", "uv"];
  59929. options.uniforms = options.uniforms || ["worldViewProjection"];
  59930. options.uniformBuffers = options.uniformBuffers || [];
  59931. options.samplers = options.samplers || [];
  59932. options.defines = options.defines || [];
  59933. _this._options = options;
  59934. return _this;
  59935. }
  59936. ShaderMaterial.prototype.getClassName = function () {
  59937. return "ShaderMaterial";
  59938. };
  59939. ShaderMaterial.prototype.needAlphaBlending = function () {
  59940. return this._options.needAlphaBlending;
  59941. };
  59942. ShaderMaterial.prototype.needAlphaTesting = function () {
  59943. return this._options.needAlphaTesting;
  59944. };
  59945. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59946. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59947. this._options.uniforms.push(uniformName);
  59948. }
  59949. };
  59950. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59951. if (this._options.samplers.indexOf(name) === -1) {
  59952. this._options.samplers.push(name);
  59953. }
  59954. this._textures[name] = texture;
  59955. return this;
  59956. };
  59957. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59958. if (this._options.samplers.indexOf(name) === -1) {
  59959. this._options.samplers.push(name);
  59960. }
  59961. this._checkUniform(name);
  59962. this._textureArrays[name] = textures;
  59963. return this;
  59964. };
  59965. ShaderMaterial.prototype.setFloat = function (name, value) {
  59966. this._checkUniform(name);
  59967. this._floats[name] = value;
  59968. return this;
  59969. };
  59970. ShaderMaterial.prototype.setInt = function (name, value) {
  59971. this._checkUniform(name);
  59972. this._ints[name] = value;
  59973. return this;
  59974. };
  59975. ShaderMaterial.prototype.setFloats = function (name, value) {
  59976. this._checkUniform(name);
  59977. this._floatsArrays[name] = value;
  59978. return this;
  59979. };
  59980. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59981. this._checkUniform(name);
  59982. this._colors3[name] = value;
  59983. return this;
  59984. };
  59985. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59986. this._checkUniform(name);
  59987. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59988. color.toArray(arr, arr.length);
  59989. return arr;
  59990. }, []);
  59991. return this;
  59992. };
  59993. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59994. this._checkUniform(name);
  59995. this._colors4[name] = value;
  59996. return this;
  59997. };
  59998. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59999. this._checkUniform(name);
  60000. this._vectors2[name] = value;
  60001. return this;
  60002. };
  60003. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60004. this._checkUniform(name);
  60005. this._vectors3[name] = value;
  60006. return this;
  60007. };
  60008. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60009. this._checkUniform(name);
  60010. this._vectors4[name] = value;
  60011. return this;
  60012. };
  60013. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60014. this._checkUniform(name);
  60015. this._matrices[name] = value;
  60016. return this;
  60017. };
  60018. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60019. this._checkUniform(name);
  60020. this._matrices3x3[name] = value;
  60021. return this;
  60022. };
  60023. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60024. this._checkUniform(name);
  60025. this._matrices2x2[name] = value;
  60026. return this;
  60027. };
  60028. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60029. this._checkUniform(name);
  60030. this._vectors2Arrays[name] = value;
  60031. return this;
  60032. };
  60033. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60034. this._checkUniform(name);
  60035. this._vectors3Arrays[name] = value;
  60036. return this;
  60037. };
  60038. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60039. if (!mesh) {
  60040. return true;
  60041. }
  60042. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60043. return false;
  60044. }
  60045. return false;
  60046. };
  60047. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60048. var scene = this.getScene();
  60049. var engine = scene.getEngine();
  60050. if (!this.checkReadyOnEveryCall) {
  60051. if (this._renderId === scene.getRenderId()) {
  60052. if (this._checkCache(scene, mesh, useInstances)) {
  60053. return true;
  60054. }
  60055. }
  60056. }
  60057. // Instances
  60058. var defines = [];
  60059. var attribs = [];
  60060. var fallbacks = new BABYLON.EffectFallbacks();
  60061. if (useInstances) {
  60062. defines.push("#define INSTANCES");
  60063. }
  60064. for (var index = 0; index < this._options.defines.length; index++) {
  60065. defines.push(this._options.defines[index]);
  60066. }
  60067. for (var index = 0; index < this._options.attributes.length; index++) {
  60068. attribs.push(this._options.attributes[index]);
  60069. }
  60070. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60071. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60072. defines.push("#define VERTEXCOLOR");
  60073. }
  60074. // Bones
  60075. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60078. if (mesh.numBoneInfluencers > 4) {
  60079. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60080. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60081. }
  60082. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60083. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60084. fallbacks.addCPUSkinningFallback(0, mesh);
  60085. if (this._options.uniforms.indexOf("mBones") === -1) {
  60086. this._options.uniforms.push("mBones");
  60087. }
  60088. }
  60089. else {
  60090. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60091. }
  60092. // Textures
  60093. for (var name in this._textures) {
  60094. if (!this._textures[name].isReady()) {
  60095. return false;
  60096. }
  60097. }
  60098. // Alpha test
  60099. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60100. defines.push("#define ALPHATEST");
  60101. }
  60102. var previousEffect = this._effect;
  60103. var join = defines.join("\n");
  60104. this._effect = engine.createEffect(this._shaderPath, {
  60105. attributes: attribs,
  60106. uniformsNames: this._options.uniforms,
  60107. uniformBuffersNames: this._options.uniformBuffers,
  60108. samplers: this._options.samplers,
  60109. defines: join,
  60110. fallbacks: fallbacks,
  60111. onCompiled: this.onCompiled,
  60112. onError: this.onError
  60113. }, engine);
  60114. if (!this._effect.isReady()) {
  60115. return false;
  60116. }
  60117. if (previousEffect !== this._effect) {
  60118. scene.resetCachedMaterial();
  60119. }
  60120. this._renderId = scene.getRenderId();
  60121. return true;
  60122. };
  60123. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60124. var scene = this.getScene();
  60125. if (!this._effect) {
  60126. return;
  60127. }
  60128. if (this._options.uniforms.indexOf("world") !== -1) {
  60129. this._effect.setMatrix("world", world);
  60130. }
  60131. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60132. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60133. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60134. }
  60135. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60136. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60137. }
  60138. };
  60139. ShaderMaterial.prototype.bind = function (world, mesh) {
  60140. // Std values
  60141. this.bindOnlyWorldMatrix(world);
  60142. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60143. if (this._options.uniforms.indexOf("view") !== -1) {
  60144. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60145. }
  60146. if (this._options.uniforms.indexOf("projection") !== -1) {
  60147. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60148. }
  60149. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60150. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60151. }
  60152. // Bones
  60153. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60154. var name;
  60155. // Texture
  60156. for (name in this._textures) {
  60157. this._effect.setTexture(name, this._textures[name]);
  60158. }
  60159. // Texture arrays
  60160. for (name in this._textureArrays) {
  60161. this._effect.setTextureArray(name, this._textureArrays[name]);
  60162. }
  60163. // Int
  60164. for (name in this._ints) {
  60165. this._effect.setInt(name, this._ints[name]);
  60166. }
  60167. // Float
  60168. for (name in this._floats) {
  60169. this._effect.setFloat(name, this._floats[name]);
  60170. }
  60171. // Floats
  60172. for (name in this._floatsArrays) {
  60173. this._effect.setArray(name, this._floatsArrays[name]);
  60174. }
  60175. // Color3
  60176. for (name in this._colors3) {
  60177. this._effect.setColor3(name, this._colors3[name]);
  60178. }
  60179. for (name in this._colors3Arrays) {
  60180. this._effect.setArray3(name, this._colors3Arrays[name]);
  60181. }
  60182. // Color4
  60183. for (name in this._colors4) {
  60184. var color = this._colors4[name];
  60185. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60186. }
  60187. // Vector2
  60188. for (name in this._vectors2) {
  60189. this._effect.setVector2(name, this._vectors2[name]);
  60190. }
  60191. // Vector3
  60192. for (name in this._vectors3) {
  60193. this._effect.setVector3(name, this._vectors3[name]);
  60194. }
  60195. // Vector4
  60196. for (name in this._vectors4) {
  60197. this._effect.setVector4(name, this._vectors4[name]);
  60198. }
  60199. // Matrix
  60200. for (name in this._matrices) {
  60201. this._effect.setMatrix(name, this._matrices[name]);
  60202. }
  60203. // Matrix 3x3
  60204. for (name in this._matrices3x3) {
  60205. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60206. }
  60207. // Matrix 2x2
  60208. for (name in this._matrices2x2) {
  60209. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60210. }
  60211. // Vector2Array
  60212. for (name in this._vectors2Arrays) {
  60213. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60214. }
  60215. // Vector3Array
  60216. for (name in this._vectors3Arrays) {
  60217. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60218. }
  60219. }
  60220. this._afterBind(mesh);
  60221. };
  60222. ShaderMaterial.prototype.getActiveTextures = function () {
  60223. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60224. for (var name in this._textures) {
  60225. activeTextures.push(this._textures[name]);
  60226. }
  60227. for (var name in this._textureArrays) {
  60228. var array = this._textureArrays[name];
  60229. for (var index = 0; index < array.length; index++) {
  60230. activeTextures.push(array[index]);
  60231. }
  60232. }
  60233. return activeTextures;
  60234. };
  60235. ShaderMaterial.prototype.hasTexture = function (texture) {
  60236. if (_super.prototype.hasTexture.call(this, texture)) {
  60237. return true;
  60238. }
  60239. for (var name in this._textures) {
  60240. if (this._textures[name] === texture) {
  60241. return true;
  60242. }
  60243. }
  60244. for (var name in this._textureArrays) {
  60245. var array = this._textureArrays[name];
  60246. for (var index = 0; index < array.length; index++) {
  60247. if (array[index] === texture) {
  60248. return true;
  60249. }
  60250. }
  60251. }
  60252. return false;
  60253. };
  60254. ShaderMaterial.prototype.clone = function (name) {
  60255. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60256. return newShaderMaterial;
  60257. };
  60258. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60259. if (forceDisposeTextures) {
  60260. var name;
  60261. for (name in this._textures) {
  60262. this._textures[name].dispose();
  60263. }
  60264. for (name in this._textureArrays) {
  60265. var array = this._textureArrays[name];
  60266. for (var index = 0; index < array.length; index++) {
  60267. array[index].dispose();
  60268. }
  60269. }
  60270. }
  60271. this._textures = {};
  60272. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60273. };
  60274. ShaderMaterial.prototype.serialize = function () {
  60275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60276. serializationObject.customType = "BABYLON.ShaderMaterial";
  60277. serializationObject.options = this._options;
  60278. serializationObject.shaderPath = this._shaderPath;
  60279. var name;
  60280. // Texture
  60281. serializationObject.textures = {};
  60282. for (name in this._textures) {
  60283. serializationObject.textures[name] = this._textures[name].serialize();
  60284. }
  60285. // Texture arrays
  60286. serializationObject.textureArrays = {};
  60287. for (name in this._textureArrays) {
  60288. serializationObject.textureArrays[name] = [];
  60289. var array = this._textureArrays[name];
  60290. for (var index = 0; index < array.length; index++) {
  60291. serializationObject.textureArrays[name].push(array[index].serialize());
  60292. }
  60293. }
  60294. // Float
  60295. serializationObject.floats = {};
  60296. for (name in this._floats) {
  60297. serializationObject.floats[name] = this._floats[name];
  60298. }
  60299. // Float s
  60300. serializationObject.FloatArrays = {};
  60301. for (name in this._floatsArrays) {
  60302. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60303. }
  60304. // Color3
  60305. serializationObject.colors3 = {};
  60306. for (name in this._colors3) {
  60307. serializationObject.colors3[name] = this._colors3[name].asArray();
  60308. }
  60309. // Color3 array
  60310. serializationObject.colors3Arrays = {};
  60311. for (name in this._colors3Arrays) {
  60312. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60313. }
  60314. // Color4
  60315. serializationObject.colors4 = {};
  60316. for (name in this._colors4) {
  60317. serializationObject.colors4[name] = this._colors4[name].asArray();
  60318. }
  60319. // Vector2
  60320. serializationObject.vectors2 = {};
  60321. for (name in this._vectors2) {
  60322. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60323. }
  60324. // Vector3
  60325. serializationObject.vectors3 = {};
  60326. for (name in this._vectors3) {
  60327. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60328. }
  60329. // Vector4
  60330. serializationObject.vectors4 = {};
  60331. for (name in this._vectors4) {
  60332. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60333. }
  60334. // Matrix
  60335. serializationObject.matrices = {};
  60336. for (name in this._matrices) {
  60337. serializationObject.matrices[name] = this._matrices[name].asArray();
  60338. }
  60339. // Matrix 3x3
  60340. serializationObject.matrices3x3 = {};
  60341. for (name in this._matrices3x3) {
  60342. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60343. }
  60344. // Matrix 2x2
  60345. serializationObject.matrices2x2 = {};
  60346. for (name in this._matrices2x2) {
  60347. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60348. }
  60349. // Vector2Array
  60350. serializationObject.vectors2Arrays = {};
  60351. for (name in this._vectors2Arrays) {
  60352. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60353. }
  60354. // Vector3Array
  60355. serializationObject.vectors3Arrays = {};
  60356. for (name in this._vectors3Arrays) {
  60357. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60358. }
  60359. return serializationObject;
  60360. };
  60361. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60362. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60363. var name;
  60364. // Texture
  60365. for (name in source.textures) {
  60366. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60367. }
  60368. // Texture arrays
  60369. for (name in source.textureArrays) {
  60370. var array = source.textureArrays[name];
  60371. var textureArray = new Array();
  60372. for (var index = 0; index < array.length; index++) {
  60373. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60374. }
  60375. material.setTextureArray(name, textureArray);
  60376. }
  60377. // Float
  60378. for (name in source.floats) {
  60379. material.setFloat(name, source.floats[name]);
  60380. }
  60381. // Float s
  60382. for (name in source.floatsArrays) {
  60383. material.setFloats(name, source.floatsArrays[name]);
  60384. }
  60385. // Color3
  60386. for (name in source.colors3) {
  60387. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60388. }
  60389. // Color3 arrays
  60390. for (name in source.colors3Arrays) {
  60391. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60392. if (i % 3 === 0) {
  60393. arr.push([num]);
  60394. }
  60395. else {
  60396. arr[arr.length - 1].push(num);
  60397. }
  60398. return arr;
  60399. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60400. material.setColor3Array(name, colors);
  60401. }
  60402. // Color4
  60403. for (name in source.colors4) {
  60404. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60405. }
  60406. // Vector2
  60407. for (name in source.vectors2) {
  60408. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60409. }
  60410. // Vector3
  60411. for (name in source.vectors3) {
  60412. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60413. }
  60414. // Vector4
  60415. for (name in source.vectors4) {
  60416. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60417. }
  60418. // Matrix
  60419. for (name in source.matrices) {
  60420. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60421. }
  60422. // Matrix 3x3
  60423. for (name in source.matrices3x3) {
  60424. material.setMatrix3x3(name, source.matrices3x3[name]);
  60425. }
  60426. // Matrix 2x2
  60427. for (name in source.matrices2x2) {
  60428. material.setMatrix2x2(name, source.matrices2x2[name]);
  60429. }
  60430. // Vector2Array
  60431. for (name in source.vectors2Arrays) {
  60432. material.setArray2(name, source.vectors2Arrays[name]);
  60433. }
  60434. // Vector3Array
  60435. for (name in source.vectors3Arrays) {
  60436. material.setArray3(name, source.vectors3Arrays[name]);
  60437. }
  60438. return material;
  60439. };
  60440. return ShaderMaterial;
  60441. }(BABYLON.Material));
  60442. BABYLON.ShaderMaterial = ShaderMaterial;
  60443. })(BABYLON || (BABYLON = {}));
  60444. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60445. var BABYLON;
  60446. (function (BABYLON) {
  60447. var GroundMesh = /** @class */ (function (_super) {
  60448. __extends(GroundMesh, _super);
  60449. function GroundMesh(name, scene) {
  60450. var _this = _super.call(this, name, scene) || this;
  60451. _this.generateOctree = false;
  60452. return _this;
  60453. }
  60454. GroundMesh.prototype.getClassName = function () {
  60455. return "GroundMesh";
  60456. };
  60457. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60458. get: function () {
  60459. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60460. },
  60461. enumerable: true,
  60462. configurable: true
  60463. });
  60464. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60465. get: function () {
  60466. return this._subdivisionsX;
  60467. },
  60468. enumerable: true,
  60469. configurable: true
  60470. });
  60471. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60472. get: function () {
  60473. return this._subdivisionsY;
  60474. },
  60475. enumerable: true,
  60476. configurable: true
  60477. });
  60478. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60479. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60480. this._subdivisionsX = chunksCount;
  60481. this._subdivisionsY = chunksCount;
  60482. this.subdivide(chunksCount);
  60483. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60484. };
  60485. /**
  60486. * Returns a height (y) value in the Worl system :
  60487. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60488. * Returns the ground y position if (x, z) are outside the ground surface.
  60489. */
  60490. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60491. var world = this.getWorldMatrix();
  60492. var invMat = BABYLON.Tmp.Matrix[5];
  60493. world.invertToRef(invMat);
  60494. var tmpVect = BABYLON.Tmp.Vector3[8];
  60495. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60496. x = tmpVect.x;
  60497. z = tmpVect.z;
  60498. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60499. return this.position.y;
  60500. }
  60501. if (!this._heightQuads || this._heightQuads.length == 0) {
  60502. this._initHeightQuads();
  60503. this._computeHeightQuads();
  60504. }
  60505. var facet = this._getFacetAt(x, z);
  60506. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60507. // return y in the World system
  60508. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60509. return tmpVect.y;
  60510. };
  60511. /**
  60512. * Returns a normalized vector (Vector3) orthogonal to the ground
  60513. * at the ground coordinates (x, z) expressed in the World system.
  60514. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60515. */
  60516. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60517. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60518. this.getNormalAtCoordinatesToRef(x, z, normal);
  60519. return normal;
  60520. };
  60521. /**
  60522. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60523. * at the ground coordinates (x, z) expressed in the World system.
  60524. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60525. * Returns the GroundMesh.
  60526. */
  60527. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60528. var world = this.getWorldMatrix();
  60529. var tmpMat = BABYLON.Tmp.Matrix[5];
  60530. world.invertToRef(tmpMat);
  60531. var tmpVect = BABYLON.Tmp.Vector3[8];
  60532. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60533. x = tmpVect.x;
  60534. z = tmpVect.z;
  60535. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60536. return this;
  60537. }
  60538. if (!this._heightQuads || this._heightQuads.length == 0) {
  60539. this._initHeightQuads();
  60540. this._computeHeightQuads();
  60541. }
  60542. var facet = this._getFacetAt(x, z);
  60543. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60544. return this;
  60545. };
  60546. /**
  60547. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60548. * if the ground has been updated.
  60549. * This can be used in the render loop.
  60550. * Returns the GroundMesh.
  60551. */
  60552. GroundMesh.prototype.updateCoordinateHeights = function () {
  60553. if (!this._heightQuads || this._heightQuads.length == 0) {
  60554. this._initHeightQuads();
  60555. }
  60556. this._computeHeightQuads();
  60557. return this;
  60558. };
  60559. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60560. GroundMesh.prototype._getFacetAt = function (x, z) {
  60561. // retrieve col and row from x, z coordinates in the ground local system
  60562. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60563. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60564. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60565. var facet;
  60566. if (z < quad.slope.x * x + quad.slope.y) {
  60567. facet = quad.facet1;
  60568. }
  60569. else {
  60570. facet = quad.facet2;
  60571. }
  60572. return facet;
  60573. };
  60574. // Creates and populates the heightMap array with "facet" elements :
  60575. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60576. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60577. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60578. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60579. // Returns the GroundMesh.
  60580. GroundMesh.prototype._initHeightQuads = function () {
  60581. var subdivisionsX = this._subdivisionsX;
  60582. var subdivisionsY = this._subdivisionsY;
  60583. this._heightQuads = new Array();
  60584. for (var row = 0; row < subdivisionsY; row++) {
  60585. for (var col = 0; col < subdivisionsX; col++) {
  60586. 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) };
  60587. this._heightQuads[row * subdivisionsX + col] = quad;
  60588. }
  60589. }
  60590. return this;
  60591. };
  60592. // Compute each quad element values and update the the heightMap array :
  60593. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60594. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60595. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60596. // Returns the GroundMesh.
  60597. GroundMesh.prototype._computeHeightQuads = function () {
  60598. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60599. if (!positions) {
  60600. return this;
  60601. }
  60602. var v1 = BABYLON.Tmp.Vector3[3];
  60603. var v2 = BABYLON.Tmp.Vector3[2];
  60604. var v3 = BABYLON.Tmp.Vector3[1];
  60605. var v4 = BABYLON.Tmp.Vector3[0];
  60606. var v1v2 = BABYLON.Tmp.Vector3[4];
  60607. var v1v3 = BABYLON.Tmp.Vector3[5];
  60608. var v1v4 = BABYLON.Tmp.Vector3[6];
  60609. var norm1 = BABYLON.Tmp.Vector3[7];
  60610. var norm2 = BABYLON.Tmp.Vector3[8];
  60611. var i = 0;
  60612. var j = 0;
  60613. var k = 0;
  60614. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60615. var h = 0;
  60616. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60617. var d2 = 0;
  60618. var subdivisionsX = this._subdivisionsX;
  60619. var subdivisionsY = this._subdivisionsY;
  60620. for (var row = 0; row < subdivisionsY; row++) {
  60621. for (var col = 0; col < subdivisionsX; col++) {
  60622. i = col * 3;
  60623. j = row * (subdivisionsX + 1) * 3;
  60624. k = (row + 1) * (subdivisionsX + 1) * 3;
  60625. v1.x = positions[j + i];
  60626. v1.y = positions[j + i + 1];
  60627. v1.z = positions[j + i + 2];
  60628. v2.x = positions[j + i + 3];
  60629. v2.y = positions[j + i + 4];
  60630. v2.z = positions[j + i + 5];
  60631. v3.x = positions[k + i];
  60632. v3.y = positions[k + i + 1];
  60633. v3.z = positions[k + i + 2];
  60634. v4.x = positions[k + i + 3];
  60635. v4.y = positions[k + i + 4];
  60636. v4.z = positions[k + i + 5];
  60637. // 2D slope V1V4
  60638. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60639. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60640. // facet equations :
  60641. // we compute each facet normal vector
  60642. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60643. // we compute the value d by applying the equation to v1 which belongs to the plane
  60644. // then we store the facet equation in a Vector4
  60645. v2.subtractToRef(v1, v1v2);
  60646. v3.subtractToRef(v1, v1v3);
  60647. v4.subtractToRef(v1, v1v4);
  60648. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60649. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60650. norm1.normalize();
  60651. norm2.normalize();
  60652. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60653. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60654. var quad = this._heightQuads[row * subdivisionsX + col];
  60655. quad.slope.copyFromFloats(cd, h);
  60656. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60657. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60658. }
  60659. }
  60660. return this;
  60661. };
  60662. GroundMesh.prototype.serialize = function (serializationObject) {
  60663. _super.prototype.serialize.call(this, serializationObject);
  60664. serializationObject.subdivisionsX = this._subdivisionsX;
  60665. serializationObject.subdivisionsY = this._subdivisionsY;
  60666. serializationObject.minX = this._minX;
  60667. serializationObject.maxX = this._maxX;
  60668. serializationObject.minZ = this._minZ;
  60669. serializationObject.maxZ = this._maxZ;
  60670. serializationObject.width = this._width;
  60671. serializationObject.height = this._height;
  60672. };
  60673. GroundMesh.Parse = function (parsedMesh, scene) {
  60674. var result = new GroundMesh(parsedMesh.name, scene);
  60675. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60676. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60677. result._minX = parsedMesh.minX;
  60678. result._maxX = parsedMesh.maxX;
  60679. result._minZ = parsedMesh.minZ;
  60680. result._maxZ = parsedMesh.maxZ;
  60681. result._width = parsedMesh.width;
  60682. result._height = parsedMesh.height;
  60683. return result;
  60684. };
  60685. return GroundMesh;
  60686. }(BABYLON.Mesh));
  60687. BABYLON.GroundMesh = GroundMesh;
  60688. })(BABYLON || (BABYLON = {}));
  60689. //# sourceMappingURL=babylon.groundMesh.js.map
  60690. var BABYLON;
  60691. (function (BABYLON) {
  60692. /**
  60693. * Creates an instance based on a source mesh.
  60694. */
  60695. var InstancedMesh = /** @class */ (function (_super) {
  60696. __extends(InstancedMesh, _super);
  60697. function InstancedMesh(name, source) {
  60698. var _this = _super.call(this, name, source.getScene()) || this;
  60699. source.instances.push(_this);
  60700. _this._sourceMesh = source;
  60701. _this.position.copyFrom(source.position);
  60702. _this.rotation.copyFrom(source.rotation);
  60703. _this.scaling.copyFrom(source.scaling);
  60704. if (source.rotationQuaternion) {
  60705. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60706. }
  60707. _this.infiniteDistance = source.infiniteDistance;
  60708. _this.setPivotMatrix(source.getPivotMatrix());
  60709. _this.refreshBoundingInfo();
  60710. _this._syncSubMeshes();
  60711. return _this;
  60712. }
  60713. /**
  60714. * Returns the string "InstancedMesh".
  60715. */
  60716. InstancedMesh.prototype.getClassName = function () {
  60717. return "InstancedMesh";
  60718. };
  60719. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60720. // Methods
  60721. get: function () {
  60722. return this._sourceMesh.receiveShadows;
  60723. },
  60724. enumerable: true,
  60725. configurable: true
  60726. });
  60727. Object.defineProperty(InstancedMesh.prototype, "material", {
  60728. get: function () {
  60729. return this._sourceMesh.material;
  60730. },
  60731. enumerable: true,
  60732. configurable: true
  60733. });
  60734. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60735. get: function () {
  60736. return this._sourceMesh.visibility;
  60737. },
  60738. enumerable: true,
  60739. configurable: true
  60740. });
  60741. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60742. get: function () {
  60743. return this._sourceMesh.skeleton;
  60744. },
  60745. enumerable: true,
  60746. configurable: true
  60747. });
  60748. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60749. get: function () {
  60750. return this._sourceMesh.renderingGroupId;
  60751. },
  60752. set: function (value) {
  60753. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60754. return;
  60755. }
  60756. //no-op with warning
  60757. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60758. },
  60759. enumerable: true,
  60760. configurable: true
  60761. });
  60762. /**
  60763. * Returns the total number of vertices (integer).
  60764. */
  60765. InstancedMesh.prototype.getTotalVertices = function () {
  60766. return this._sourceMesh.getTotalVertices();
  60767. };
  60768. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60769. get: function () {
  60770. return this._sourceMesh;
  60771. },
  60772. enumerable: true,
  60773. configurable: true
  60774. });
  60775. /**
  60776. * Is this node ready to be used/rendered
  60777. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60778. * @return {boolean} is it ready
  60779. */
  60780. InstancedMesh.prototype.isReady = function (completeCheck) {
  60781. if (completeCheck === void 0) { completeCheck = false; }
  60782. return this._sourceMesh.isReady(completeCheck, true);
  60783. };
  60784. /**
  60785. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60786. */
  60787. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60788. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60789. };
  60790. /**
  60791. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60792. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60793. * The `data` are either a numeric array either a Float32Array.
  60794. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60795. * 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).
  60796. * Note that a new underlying VertexBuffer object is created each call.
  60797. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60798. *
  60799. * Possible `kind` values :
  60800. * - BABYLON.VertexBuffer.PositionKind
  60801. * - BABYLON.VertexBuffer.UVKind
  60802. * - BABYLON.VertexBuffer.UV2Kind
  60803. * - BABYLON.VertexBuffer.UV3Kind
  60804. * - BABYLON.VertexBuffer.UV4Kind
  60805. * - BABYLON.VertexBuffer.UV5Kind
  60806. * - BABYLON.VertexBuffer.UV6Kind
  60807. * - BABYLON.VertexBuffer.ColorKind
  60808. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60809. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60810. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60811. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60812. *
  60813. * Returns the Mesh.
  60814. */
  60815. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60816. if (this.sourceMesh) {
  60817. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60818. }
  60819. return this.sourceMesh;
  60820. };
  60821. /**
  60822. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60823. * If the mesh has no geometry, it is simply returned as it is.
  60824. * The `data` are either a numeric array either a Float32Array.
  60825. * No new underlying VertexBuffer object is created.
  60826. * 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.
  60827. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60828. *
  60829. * Possible `kind` values :
  60830. * - BABYLON.VertexBuffer.PositionKind
  60831. * - BABYLON.VertexBuffer.UVKind
  60832. * - BABYLON.VertexBuffer.UV2Kind
  60833. * - BABYLON.VertexBuffer.UV3Kind
  60834. * - BABYLON.VertexBuffer.UV4Kind
  60835. * - BABYLON.VertexBuffer.UV5Kind
  60836. * - BABYLON.VertexBuffer.UV6Kind
  60837. * - BABYLON.VertexBuffer.ColorKind
  60838. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60839. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60840. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60841. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60842. *
  60843. * Returns the Mesh.
  60844. */
  60845. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60846. if (this.sourceMesh) {
  60847. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60848. }
  60849. return this.sourceMesh;
  60850. };
  60851. /**
  60852. * Sets the mesh indices.
  60853. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60854. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60855. * This method creates a new index buffer each call.
  60856. * Returns the Mesh.
  60857. */
  60858. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60859. if (totalVertices === void 0) { totalVertices = null; }
  60860. if (this.sourceMesh) {
  60861. this.sourceMesh.setIndices(indices, totalVertices);
  60862. }
  60863. return this.sourceMesh;
  60864. };
  60865. /**
  60866. * Boolean : True if the mesh owns the requested kind of data.
  60867. */
  60868. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60869. return this._sourceMesh.isVerticesDataPresent(kind);
  60870. };
  60871. /**
  60872. * Returns an array of indices (IndicesArray).
  60873. */
  60874. InstancedMesh.prototype.getIndices = function () {
  60875. return this._sourceMesh.getIndices();
  60876. };
  60877. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60878. get: function () {
  60879. return this._sourceMesh._positions;
  60880. },
  60881. enumerable: true,
  60882. configurable: true
  60883. });
  60884. /**
  60885. * Sets a new updated BoundingInfo to the mesh.
  60886. * Returns the mesh.
  60887. */
  60888. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60889. var meshBB = this._sourceMesh.getBoundingInfo();
  60890. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60891. this._updateBoundingInfo();
  60892. return this;
  60893. };
  60894. InstancedMesh.prototype._preActivate = function () {
  60895. if (this._currentLOD) {
  60896. this._currentLOD._preActivate();
  60897. }
  60898. return this;
  60899. };
  60900. InstancedMesh.prototype._activate = function (renderId) {
  60901. if (this._currentLOD) {
  60902. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60903. }
  60904. return this;
  60905. };
  60906. /**
  60907. * Returns the current associated LOD AbstractMesh.
  60908. */
  60909. InstancedMesh.prototype.getLOD = function (camera) {
  60910. if (!camera) {
  60911. return this;
  60912. }
  60913. var boundingInfo = this.getBoundingInfo();
  60914. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60915. if (this._currentLOD === this.sourceMesh) {
  60916. return this;
  60917. }
  60918. return this._currentLOD;
  60919. };
  60920. InstancedMesh.prototype._syncSubMeshes = function () {
  60921. this.releaseSubMeshes();
  60922. if (this._sourceMesh.subMeshes) {
  60923. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60924. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60925. }
  60926. }
  60927. return this;
  60928. };
  60929. InstancedMesh.prototype._generatePointsArray = function () {
  60930. return this._sourceMesh._generatePointsArray();
  60931. };
  60932. /**
  60933. * Creates a new InstancedMesh from the current mesh.
  60934. * - name (string) : the cloned mesh name
  60935. * - newParent (optional Node) : the optional Node to parent the clone to.
  60936. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60937. *
  60938. * Returns the clone.
  60939. */
  60940. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60941. var result = this._sourceMesh.createInstance(name);
  60942. // Deep copy
  60943. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60944. // Bounding info
  60945. this.refreshBoundingInfo();
  60946. // Parent
  60947. if (newParent) {
  60948. result.parent = newParent;
  60949. }
  60950. if (!doNotCloneChildren) {
  60951. // Children
  60952. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60953. var mesh = this.getScene().meshes[index];
  60954. if (mesh.parent === this) {
  60955. mesh.clone(mesh.name, result);
  60956. }
  60957. }
  60958. }
  60959. result.computeWorldMatrix(true);
  60960. return result;
  60961. };
  60962. /**
  60963. * Disposes the InstancedMesh.
  60964. * Returns nothing.
  60965. */
  60966. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60967. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60968. // Remove from mesh
  60969. var index = this._sourceMesh.instances.indexOf(this);
  60970. this._sourceMesh.instances.splice(index, 1);
  60971. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60972. };
  60973. return InstancedMesh;
  60974. }(BABYLON.AbstractMesh));
  60975. BABYLON.InstancedMesh = InstancedMesh;
  60976. })(BABYLON || (BABYLON = {}));
  60977. //# sourceMappingURL=babylon.instancedMesh.js.map
  60978. var BABYLON;
  60979. (function (BABYLON) {
  60980. var LinesMesh = /** @class */ (function (_super) {
  60981. __extends(LinesMesh, _super);
  60982. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60983. if (scene === void 0) { scene = null; }
  60984. if (parent === void 0) { parent = null; }
  60985. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60986. _this.useVertexColor = useVertexColor;
  60987. _this.useVertexAlpha = useVertexAlpha;
  60988. _this.color = new BABYLON.Color3(1, 1, 1);
  60989. _this.alpha = 1;
  60990. if (source) {
  60991. _this.color = source.color.clone();
  60992. _this.alpha = source.alpha;
  60993. _this.useVertexColor = source.useVertexColor;
  60994. _this.useVertexAlpha = source.useVertexAlpha;
  60995. }
  60996. _this._intersectionThreshold = 0.1;
  60997. var defines = [];
  60998. var options = {
  60999. attributes: [BABYLON.VertexBuffer.PositionKind],
  61000. uniforms: ["world", "viewProjection"],
  61001. needAlphaBlending: true,
  61002. defines: defines
  61003. };
  61004. if (useVertexAlpha === false) {
  61005. options.needAlphaBlending = false;
  61006. }
  61007. if (!useVertexColor) {
  61008. options.uniforms.push("color");
  61009. }
  61010. else {
  61011. options.defines.push("#define VERTEXCOLOR");
  61012. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61013. }
  61014. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61015. return _this;
  61016. }
  61017. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61018. /**
  61019. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61020. * This margin is expressed in world space coordinates, so its value may vary.
  61021. * Default value is 0.1
  61022. * @returns the intersection Threshold value.
  61023. */
  61024. get: function () {
  61025. return this._intersectionThreshold;
  61026. },
  61027. /**
  61028. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61029. * This margin is expressed in world space coordinates, so its value may vary.
  61030. * @param value the new threshold to apply
  61031. */
  61032. set: function (value) {
  61033. if (this._intersectionThreshold === value) {
  61034. return;
  61035. }
  61036. this._intersectionThreshold = value;
  61037. if (this.geometry) {
  61038. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61039. }
  61040. },
  61041. enumerable: true,
  61042. configurable: true
  61043. });
  61044. /**
  61045. * Returns the string "LineMesh"
  61046. */
  61047. LinesMesh.prototype.getClassName = function () {
  61048. return "LinesMesh";
  61049. };
  61050. Object.defineProperty(LinesMesh.prototype, "material", {
  61051. get: function () {
  61052. return this._colorShader;
  61053. },
  61054. set: function (value) {
  61055. // Do nothing
  61056. },
  61057. enumerable: true,
  61058. configurable: true
  61059. });
  61060. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61061. get: function () {
  61062. return false;
  61063. },
  61064. enumerable: true,
  61065. configurable: true
  61066. });
  61067. LinesMesh.prototype.createInstance = function (name) {
  61068. throw new Error("LinesMeshes do not support createInstance.");
  61069. };
  61070. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61071. if (!this._geometry) {
  61072. return this;
  61073. }
  61074. // VBOs
  61075. this._geometry._bind(this._colorShader.getEffect());
  61076. // Color
  61077. if (!this.useVertexColor) {
  61078. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61079. }
  61080. return this;
  61081. };
  61082. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61083. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61084. return this;
  61085. }
  61086. var engine = this.getScene().getEngine();
  61087. // Draw order
  61088. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61089. return this;
  61090. };
  61091. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61092. this._colorShader.dispose();
  61093. _super.prototype.dispose.call(this, doNotRecurse);
  61094. };
  61095. /**
  61096. * Returns a new LineMesh object cloned from the current one.
  61097. */
  61098. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61099. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61100. };
  61101. return LinesMesh;
  61102. }(BABYLON.Mesh));
  61103. BABYLON.LinesMesh = LinesMesh;
  61104. })(BABYLON || (BABYLON = {}));
  61105. //# sourceMappingURL=babylon.linesMesh.js.map
  61106. var BABYLON;
  61107. (function (BABYLON) {
  61108. /**
  61109. * Class containing static functions to help procedurally build meshes
  61110. */
  61111. var MeshBuilder = /** @class */ (function () {
  61112. function MeshBuilder() {
  61113. }
  61114. MeshBuilder.updateSideOrientation = function (orientation) {
  61115. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61116. return BABYLON.Mesh.DOUBLESIDE;
  61117. }
  61118. if (orientation === undefined || orientation === null) {
  61119. return BABYLON.Mesh.FRONTSIDE;
  61120. }
  61121. return orientation;
  61122. };
  61123. /**
  61124. * Creates a box mesh
  61125. * * The parameter `size` sets the size (float) of each box side (default 1)
  61126. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61127. * * 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)
  61128. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61129. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61130. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61131. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61132. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61133. * @param name defines the name of the mesh
  61134. * @param options defines the options used to create the mesh
  61135. * @param scene defines the hosting scene
  61136. * @returns the box mesh
  61137. */
  61138. MeshBuilder.CreateBox = function (name, options, scene) {
  61139. if (scene === void 0) { scene = null; }
  61140. var box = new BABYLON.Mesh(name, scene);
  61141. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61142. box._originalBuilderSideOrientation = options.sideOrientation;
  61143. var vertexData = BABYLON.VertexData.CreateBox(options);
  61144. vertexData.applyToMesh(box, options.updatable);
  61145. return box;
  61146. };
  61147. /**
  61148. * Creates a sphere mesh
  61149. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61150. * * 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`)
  61151. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61152. * * 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
  61153. * * 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)
  61154. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61155. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61156. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61157. * @param name defines the name of the mesh
  61158. * @param options defines the options used to create the mesh
  61159. * @param scene defines the hosting scene
  61160. * @returns the sphere mesh
  61161. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61162. */
  61163. MeshBuilder.CreateSphere = function (name, options, scene) {
  61164. var sphere = new BABYLON.Mesh(name, scene);
  61165. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61166. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61167. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61168. vertexData.applyToMesh(sphere, options.updatable);
  61169. return sphere;
  61170. };
  61171. /**
  61172. * Creates a plane polygonal mesh. By default, this is a disc
  61173. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61174. * * 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
  61175. * * 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
  61176. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61177. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61178. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61179. * @param name defines the name of the mesh
  61180. * @param options defines the options used to create the mesh
  61181. * @param scene defines the hosting scene
  61182. * @returns the plane polygonal mesh
  61183. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61184. */
  61185. MeshBuilder.CreateDisc = function (name, options, scene) {
  61186. if (scene === void 0) { scene = null; }
  61187. var disc = new BABYLON.Mesh(name, scene);
  61188. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61189. disc._originalBuilderSideOrientation = options.sideOrientation;
  61190. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61191. vertexData.applyToMesh(disc, options.updatable);
  61192. return disc;
  61193. };
  61194. /**
  61195. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61196. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61197. * * 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`)
  61198. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61199. * * 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
  61200. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61201. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61202. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61203. * @param name defines the name of the mesh
  61204. * @param options defines the options used to create the mesh
  61205. * @param scene defines the hosting scene
  61206. * @returns the icosahedron mesh
  61207. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61208. */
  61209. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61210. var sphere = new BABYLON.Mesh(name, scene);
  61211. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61212. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61213. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61214. vertexData.applyToMesh(sphere, options.updatable);
  61215. return sphere;
  61216. };
  61217. ;
  61218. /**
  61219. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61220. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61221. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61222. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61223. * * 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
  61224. * * 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
  61225. * * 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
  61226. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61227. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61228. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61229. * * 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
  61230. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61231. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  61232. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61234. * @param name defines the name of the mesh
  61235. * @param options defines the options used to create the mesh
  61236. * @param scene defines the hosting scene
  61237. * @returns the ribbon mesh
  61238. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61239. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61240. */
  61241. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61242. if (scene === void 0) { scene = null; }
  61243. var pathArray = options.pathArray;
  61244. var closeArray = options.closeArray;
  61245. var closePath = options.closePath;
  61246. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61247. var instance = options.instance;
  61248. var updatable = options.updatable;
  61249. if (instance) { // existing ribbon instance update
  61250. // positionFunction : ribbon case
  61251. // only pathArray and sideOrientation parameters are taken into account for positions update
  61252. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61253. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61254. var positionFunction = function (positions) {
  61255. var minlg = pathArray[0].length;
  61256. var i = 0;
  61257. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61258. for (var si = 1; si <= ns; si++) {
  61259. for (var p = 0; p < pathArray.length; p++) {
  61260. var path = pathArray[p];
  61261. var l = path.length;
  61262. minlg = (minlg < l) ? minlg : l;
  61263. var j = 0;
  61264. while (j < minlg) {
  61265. positions[i] = path[j].x;
  61266. positions[i + 1] = path[j].y;
  61267. positions[i + 2] = path[j].z;
  61268. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61269. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61270. }
  61271. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61272. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61273. }
  61274. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61275. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61276. }
  61277. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61278. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61279. }
  61280. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61281. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61282. }
  61283. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61284. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61285. }
  61286. j++;
  61287. i += 3;
  61288. }
  61289. if (instance._closePath) {
  61290. positions[i] = path[0].x;
  61291. positions[i + 1] = path[0].y;
  61292. positions[i + 2] = path[0].z;
  61293. i += 3;
  61294. }
  61295. }
  61296. }
  61297. };
  61298. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61299. positionFunction(positions);
  61300. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61301. instance._boundingInfo.update(instance._worldMatrix);
  61302. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61303. if (options.colors) {
  61304. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61305. for (var c = 0; c < options.colors.length; c++) {
  61306. colors[c * 4] = options.colors[c].r;
  61307. colors[c * 4 + 1] = options.colors[c].g;
  61308. colors[c * 4 + 2] = options.colors[c].b;
  61309. colors[c * 4 + 3] = options.colors[c].a;
  61310. }
  61311. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61312. }
  61313. if (options.uvs) {
  61314. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61315. for (var i = 0; i < options.uvs.length; i++) {
  61316. uvs[i * 2] = options.uvs[i].x;
  61317. uvs[i * 2 + 1] = options.uvs[i].y;
  61318. }
  61319. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61320. }
  61321. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61322. var indices = instance.getIndices();
  61323. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61324. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61325. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61326. if (instance._closePath) {
  61327. var indexFirst = 0;
  61328. var indexLast = 0;
  61329. for (var p = 0; p < pathArray.length; p++) {
  61330. indexFirst = instance._idx[p] * 3;
  61331. if (p + 1 < pathArray.length) {
  61332. indexLast = (instance._idx[p + 1] - 1) * 3;
  61333. }
  61334. else {
  61335. indexLast = normals.length - 3;
  61336. }
  61337. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61338. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61339. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61340. normals[indexLast] = normals[indexFirst];
  61341. normals[indexLast + 1] = normals[indexFirst + 1];
  61342. normals[indexLast + 2] = normals[indexFirst + 2];
  61343. }
  61344. }
  61345. if (!(instance.areNormalsFrozen)) {
  61346. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61347. }
  61348. }
  61349. return instance;
  61350. }
  61351. else { // new ribbon creation
  61352. var ribbon = new BABYLON.Mesh(name, scene);
  61353. ribbon._originalBuilderSideOrientation = sideOrientation;
  61354. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61355. if (closePath) {
  61356. ribbon._idx = vertexData._idx;
  61357. }
  61358. ribbon._closePath = closePath;
  61359. ribbon._closeArray = closeArray;
  61360. vertexData.applyToMesh(ribbon, updatable);
  61361. return ribbon;
  61362. }
  61363. };
  61364. /**
  61365. * Creates a cylinder or a cone mesh
  61366. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61367. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61368. * * 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.
  61369. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61370. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61371. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61372. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61373. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61374. * * 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).
  61375. * * 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
  61376. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61377. * * 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
  61378. * * 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.
  61379. * * If `enclose` is false, a ring surface is one element.
  61380. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61381. * * 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
  61382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61383. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61384. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61385. * @param name defines the name of the mesh
  61386. * @param options defines the options used to create the mesh
  61387. * @param scene defines the hosting scene
  61388. * @returns the cylinder mesh
  61389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61390. */
  61391. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61392. var cylinder = new BABYLON.Mesh(name, scene);
  61393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61394. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61395. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61396. vertexData.applyToMesh(cylinder, options.updatable);
  61397. return cylinder;
  61398. };
  61399. /**
  61400. * Creates a torus mesh
  61401. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61402. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61403. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61404. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61405. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61406. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61407. * @param name defines the name of the mesh
  61408. * @param options defines the options used to create the mesh
  61409. * @param scene defines the hosting scene
  61410. * @returns the torus mesh
  61411. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61412. */
  61413. MeshBuilder.CreateTorus = function (name, options, scene) {
  61414. var torus = new BABYLON.Mesh(name, scene);
  61415. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61416. torus._originalBuilderSideOrientation = options.sideOrientation;
  61417. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61418. vertexData.applyToMesh(torus, options.updatable);
  61419. return torus;
  61420. };
  61421. /**
  61422. * Creates a torus knot mesh
  61423. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61424. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61425. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61426. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61427. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61428. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61429. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61430. * @param name defines the name of the mesh
  61431. * @param options defines the options used to create the mesh
  61432. * @param scene defines the hosting scene
  61433. * @returns the torus knot mesh
  61434. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61435. */
  61436. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61437. var torusKnot = new BABYLON.Mesh(name, scene);
  61438. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61439. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61440. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61441. vertexData.applyToMesh(torusKnot, options.updatable);
  61442. return torusKnot;
  61443. };
  61444. /**
  61445. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61446. * * 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
  61447. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61448. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61449. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61450. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61451. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61452. * * 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
  61453. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61454. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61455. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61456. * @param name defines the name of the new line system
  61457. * @param options defines the options used to create the line system
  61458. * @param scene defines the hosting scene
  61459. * @returns a new line system mesh
  61460. */
  61461. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61462. var instance = options.instance;
  61463. var lines = options.lines;
  61464. var colors = options.colors;
  61465. if (instance) { // lines update
  61466. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61467. var vertexColor;
  61468. var lineColors;
  61469. if (colors) {
  61470. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61471. }
  61472. var i = 0;
  61473. var c = 0;
  61474. for (var l = 0; l < lines.length; l++) {
  61475. var points = lines[l];
  61476. for (var p = 0; p < points.length; p++) {
  61477. positions[i] = points[p].x;
  61478. positions[i + 1] = points[p].y;
  61479. positions[i + 2] = points[p].z;
  61480. if (colors && vertexColor) {
  61481. lineColors = colors[l];
  61482. vertexColor[c] = lineColors[p].r;
  61483. vertexColor[c + 1] = lineColors[p].g;
  61484. vertexColor[c + 2] = lineColors[p].b;
  61485. vertexColor[c + 3] = lineColors[p].a;
  61486. c += 4;
  61487. }
  61488. i += 3;
  61489. }
  61490. }
  61491. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61492. if (colors && vertexColor) {
  61493. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61494. }
  61495. return instance;
  61496. }
  61497. // line system creation
  61498. var useVertexColor = (colors) ? true : false;
  61499. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61500. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61501. vertexData.applyToMesh(lineSystem, options.updatable);
  61502. return lineSystem;
  61503. };
  61504. /**
  61505. * Creates a line mesh
  61506. * 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
  61507. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61508. * * The parameter `points` is an array successive Vector3
  61509. * * 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
  61510. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61511. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61512. * * When updating an instance, remember that only point positions can change, not the number of points
  61513. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61514. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61515. * @param name defines the name of the new line system
  61516. * @param options defines the options used to create the line system
  61517. * @param scene defines the hosting scene
  61518. * @returns a new line mesh
  61519. */
  61520. MeshBuilder.CreateLines = function (name, options, scene) {
  61521. if (scene === void 0) { scene = null; }
  61522. var colors = (options.colors) ? [options.colors] : null;
  61523. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61524. return lines;
  61525. };
  61526. /**
  61527. * Creates a dashed line mesh
  61528. * * 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
  61529. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61530. * * The parameter `points` is an array successive Vector3
  61531. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61532. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61533. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61534. * * 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
  61535. * * When updating an instance, remember that only point positions can change, not the number of points
  61536. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61537. * @param name defines the name of the mesh
  61538. * @param options defines the options used to create the mesh
  61539. * @param scene defines the hosting scene
  61540. * @returns the dashed line mesh
  61541. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61542. */
  61543. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61544. if (scene === void 0) { scene = null; }
  61545. var points = options.points;
  61546. var instance = options.instance;
  61547. var gapSize = options.gapSize || 1;
  61548. var dashSize = options.dashSize || 3;
  61549. if (instance) { // dashed lines update
  61550. var positionFunction = function (positions) {
  61551. var curvect = BABYLON.Vector3.Zero();
  61552. var nbSeg = positions.length / 6;
  61553. var lg = 0;
  61554. var nb = 0;
  61555. var shft = 0;
  61556. var dashshft = 0;
  61557. var curshft = 0;
  61558. var p = 0;
  61559. var i = 0;
  61560. var j = 0;
  61561. for (i = 0; i < points.length - 1; i++) {
  61562. points[i + 1].subtractToRef(points[i], curvect);
  61563. lg += curvect.length();
  61564. }
  61565. shft = lg / nbSeg;
  61566. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61567. for (i = 0; i < points.length - 1; i++) {
  61568. points[i + 1].subtractToRef(points[i], curvect);
  61569. nb = Math.floor(curvect.length() / shft);
  61570. curvect.normalize();
  61571. j = 0;
  61572. while (j < nb && p < positions.length) {
  61573. curshft = shft * j;
  61574. positions[p] = points[i].x + curshft * curvect.x;
  61575. positions[p + 1] = points[i].y + curshft * curvect.y;
  61576. positions[p + 2] = points[i].z + curshft * curvect.z;
  61577. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61578. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61579. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61580. p += 6;
  61581. j++;
  61582. }
  61583. }
  61584. while (p < positions.length) {
  61585. positions[p] = points[i].x;
  61586. positions[p + 1] = points[i].y;
  61587. positions[p + 2] = points[i].z;
  61588. p += 3;
  61589. }
  61590. };
  61591. instance.updateMeshPositions(positionFunction, false);
  61592. return instance;
  61593. }
  61594. // dashed lines creation
  61595. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61596. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61597. vertexData.applyToMesh(dashedLines, options.updatable);
  61598. dashedLines.dashSize = dashSize;
  61599. dashedLines.gapSize = gapSize;
  61600. return dashedLines;
  61601. };
  61602. /**
  61603. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61604. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61605. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61606. * * 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.
  61607. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61608. * * 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
  61609. * * 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
  61610. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61611. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61612. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61613. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61614. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61615. * @param name defines the name of the mesh
  61616. * @param options defines the options used to create the mesh
  61617. * @param scene defines the hosting scene
  61618. * @returns the extruded shape mesh
  61619. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61620. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61621. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61622. */
  61623. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61624. if (scene === void 0) { scene = null; }
  61625. var path = options.path;
  61626. var shape = options.shape;
  61627. var scale = options.scale || 1;
  61628. var rotation = options.rotation || 0;
  61629. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61630. var updatable = options.updatable;
  61631. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61632. var instance = options.instance || null;
  61633. var invertUV = options.invertUV || false;
  61634. 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);
  61635. };
  61636. /**
  61637. * Creates an custom extruded shape mesh.
  61638. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61639. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61640. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61641. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61642. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61643. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61644. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61645. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61646. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61647. * * 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
  61648. * * 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
  61649. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61650. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61651. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61652. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61653. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61654. * @param name defines the name of the mesh
  61655. * @param options defines the options used to create the mesh
  61656. * @param scene defines the hosting scene
  61657. * @returns the custom extruded shape mesh
  61658. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61659. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61660. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61661. */
  61662. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61663. var path = options.path;
  61664. var shape = options.shape;
  61665. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61666. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61667. var ribbonCloseArray = options.ribbonCloseArray || false;
  61668. var ribbonClosePath = options.ribbonClosePath || false;
  61669. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61670. var updatable = options.updatable;
  61671. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61672. var instance = options.instance;
  61673. var invertUV = options.invertUV || false;
  61674. 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);
  61675. };
  61676. /**
  61677. * Creates lathe mesh.
  61678. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61679. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61680. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61681. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61682. * * 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
  61683. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61684. * * 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
  61685. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61686. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61687. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61688. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61689. * @param name defines the name of the mesh
  61690. * @param options defines the options used to create the mesh
  61691. * @param scene defines the hosting scene
  61692. * @returns the lathe mesh
  61693. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61694. */
  61695. MeshBuilder.CreateLathe = function (name, options, scene) {
  61696. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61697. var closed = (options.closed === undefined) ? true : options.closed;
  61698. var shape = options.shape;
  61699. var radius = options.radius || 1;
  61700. var tessellation = options.tessellation || 64;
  61701. var updatable = options.updatable;
  61702. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61703. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61704. var pi2 = Math.PI * 2;
  61705. var paths = new Array();
  61706. var invertUV = options.invertUV || false;
  61707. var i = 0;
  61708. var p = 0;
  61709. var step = pi2 / tessellation * arc;
  61710. var rotated;
  61711. var path = new Array();
  61712. for (i = 0; i <= tessellation; i++) {
  61713. var path = [];
  61714. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61715. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61716. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61717. }
  61718. for (p = 0; p < shape.length; p++) {
  61719. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61720. path.push(rotated);
  61721. }
  61722. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61723. 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));
  61724. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61725. }
  61726. paths.push(path);
  61727. }
  61728. // lathe ribbon
  61729. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61730. return lathe;
  61731. };
  61732. /**
  61733. * Creates a plane mesh
  61734. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61735. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61736. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61737. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61738. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61739. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61740. * @param name defines the name of the mesh
  61741. * @param options defines the options used to create the mesh
  61742. * @param scene defines the hosting scene
  61743. * @returns the plane mesh
  61744. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61745. */
  61746. MeshBuilder.CreatePlane = function (name, options, scene) {
  61747. var plane = new BABYLON.Mesh(name, scene);
  61748. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61749. plane._originalBuilderSideOrientation = options.sideOrientation;
  61750. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61751. vertexData.applyToMesh(plane, options.updatable);
  61752. if (options.sourcePlane) {
  61753. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61754. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61755. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61756. plane.rotate(vectorProduct, product);
  61757. }
  61758. return plane;
  61759. };
  61760. /**
  61761. * Creates a ground mesh
  61762. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61763. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61764. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61765. * @param name defines the name of the mesh
  61766. * @param options defines the options used to create the mesh
  61767. * @param scene defines the hosting scene
  61768. * @returns the ground mesh
  61769. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61770. */
  61771. MeshBuilder.CreateGround = function (name, options, scene) {
  61772. var ground = new BABYLON.GroundMesh(name, scene);
  61773. ground._setReady(false);
  61774. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61775. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61776. ground._width = options.width || 1;
  61777. ground._height = options.height || 1;
  61778. ground._maxX = ground._width / 2;
  61779. ground._maxZ = ground._height / 2;
  61780. ground._minX = -ground._maxX;
  61781. ground._minZ = -ground._maxZ;
  61782. var vertexData = BABYLON.VertexData.CreateGround(options);
  61783. vertexData.applyToMesh(ground, options.updatable);
  61784. ground._setReady(true);
  61785. return ground;
  61786. };
  61787. /**
  61788. * Creates a tiled ground mesh
  61789. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61790. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61791. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61792. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61793. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61794. * @param name defines the name of the mesh
  61795. * @param options defines the options used to create the mesh
  61796. * @param scene defines the hosting scene
  61797. * @returns the tiled ground mesh
  61798. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61799. */
  61800. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61801. var tiledGround = new BABYLON.Mesh(name, scene);
  61802. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61803. vertexData.applyToMesh(tiledGround, options.updatable);
  61804. return tiledGround;
  61805. };
  61806. /**
  61807. * Creates a ground mesh from a height map
  61808. * * The parameter `url` sets the URL of the height map image resource.
  61809. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61810. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61811. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61812. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61813. * * 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.
  61814. * * 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).
  61815. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61816. * @param name defines the name of the mesh
  61817. * @param url defines the url to the height map
  61818. * @param options defines the options used to create the mesh
  61819. * @param scene defines the hosting scene
  61820. * @returns the ground mesh
  61821. * @see http://doc.babylonjs.com/babylon101/height_map
  61822. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61823. */
  61824. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61825. var width = options.width || 10.0;
  61826. var height = options.height || 10.0;
  61827. var subdivisions = options.subdivisions || 1 | 0;
  61828. var minHeight = options.minHeight || 0.0;
  61829. var maxHeight = options.maxHeight || 1.0;
  61830. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61831. var updatable = options.updatable;
  61832. var onReady = options.onReady;
  61833. var ground = new BABYLON.GroundMesh(name, scene);
  61834. ground._subdivisionsX = subdivisions;
  61835. ground._subdivisionsY = subdivisions;
  61836. ground._width = width;
  61837. ground._height = height;
  61838. ground._maxX = ground._width / 2.0;
  61839. ground._maxZ = ground._height / 2.0;
  61840. ground._minX = -ground._maxX;
  61841. ground._minZ = -ground._maxZ;
  61842. ground._setReady(false);
  61843. var onload = function (img) {
  61844. // Getting height map data
  61845. var canvas = document.createElement("canvas");
  61846. var context = canvas.getContext("2d");
  61847. if (!context) {
  61848. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61849. }
  61850. if (scene.isDisposed) {
  61851. return;
  61852. }
  61853. var bufferWidth = img.width;
  61854. var bufferHeight = img.height;
  61855. canvas.width = bufferWidth;
  61856. canvas.height = bufferHeight;
  61857. context.drawImage(img, 0, 0);
  61858. // Create VertexData from map data
  61859. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61860. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61861. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61862. width: width, height: height,
  61863. subdivisions: subdivisions,
  61864. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61865. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61866. });
  61867. vertexData.applyToMesh(ground, updatable);
  61868. //execute ready callback, if set
  61869. if (onReady) {
  61870. onReady(ground);
  61871. }
  61872. ground._setReady(true);
  61873. };
  61874. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61875. return ground;
  61876. };
  61877. /**
  61878. * Creates a polygon mesh
  61879. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61880. * * 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
  61881. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61882. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61883. * * 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)
  61884. * * Remember you can only change the shape positions, not their number when updating a polygon
  61885. * @param name defines the name of the mesh
  61886. * @param options defines the options used to create the mesh
  61887. * @param scene defines the hosting scene
  61888. * @returns the polygon mesh
  61889. */
  61890. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61891. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61892. var shape = options.shape;
  61893. var holes = options.holes || [];
  61894. var depth = options.depth || 0;
  61895. var contours = [];
  61896. var hole = [];
  61897. for (var i = 0; i < shape.length; i++) {
  61898. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61899. }
  61900. var epsilon = 0.00000001;
  61901. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61902. contours.pop();
  61903. }
  61904. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61905. for (var hNb = 0; hNb < holes.length; hNb++) {
  61906. hole = [];
  61907. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61908. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61909. }
  61910. polygonTriangulation.addHole(hole);
  61911. }
  61912. var polygon = polygonTriangulation.build(options.updatable, depth);
  61913. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61914. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61915. vertexData.applyToMesh(polygon, options.updatable);
  61916. return polygon;
  61917. };
  61918. ;
  61919. /**
  61920. * Creates an extruded polygon mesh, with depth in the Y direction.
  61921. * * 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)
  61922. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61923. * @param name defines the name of the mesh
  61924. * @param options defines the options used to create the mesh
  61925. * @param scene defines the hosting scene
  61926. * @returns the polygon mesh
  61927. */
  61928. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61929. return MeshBuilder.CreatePolygon(name, options, scene);
  61930. };
  61931. ;
  61932. /**
  61933. * Creates a tube mesh.
  61934. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61935. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61936. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61937. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61938. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61939. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61940. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61941. * * 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
  61942. * * 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
  61943. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61944. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61945. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61946. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61947. * @param name defines the name of the mesh
  61948. * @param options defines the options used to create the mesh
  61949. * @param scene defines the hosting scene
  61950. * @returns the tube mesh
  61951. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61952. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61953. */
  61954. MeshBuilder.CreateTube = function (name, options, scene) {
  61955. var path = options.path;
  61956. var instance = options.instance;
  61957. var radius = 1.0;
  61958. if (instance) {
  61959. radius = instance.radius;
  61960. }
  61961. if (options.radius !== undefined) {
  61962. radius = options.radius;
  61963. }
  61964. ;
  61965. var tessellation = options.tessellation || 64 | 0;
  61966. var radiusFunction = options.radiusFunction || null;
  61967. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61968. var invertUV = options.invertUV || false;
  61969. var updatable = options.updatable;
  61970. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61971. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61972. // tube geometry
  61973. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61974. var tangents = path3D.getTangents();
  61975. var normals = path3D.getNormals();
  61976. var distances = path3D.getDistances();
  61977. var pi2 = Math.PI * 2;
  61978. var step = pi2 / tessellation * arc;
  61979. var returnRadius = function () { return radius; };
  61980. var radiusFunctionFinal = radiusFunction || returnRadius;
  61981. var circlePath;
  61982. var rad;
  61983. var normal;
  61984. var rotated;
  61985. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61986. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61987. for (var i = 0; i < path.length; i++) {
  61988. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61989. circlePath = Array(); // current circle array
  61990. normal = normals[i]; // current normal
  61991. for (var t = 0; t < tessellation; t++) {
  61992. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61993. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61994. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61995. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61996. circlePath[t] = rotated;
  61997. }
  61998. circlePaths[index] = circlePath;
  61999. index++;
  62000. }
  62001. // cap
  62002. var capPath = function (nbPoints, pathIndex) {
  62003. var pointCap = Array();
  62004. for (var i = 0; i < nbPoints; i++) {
  62005. pointCap.push(path[pathIndex]);
  62006. }
  62007. return pointCap;
  62008. };
  62009. switch (cap) {
  62010. case BABYLON.Mesh.NO_CAP:
  62011. break;
  62012. case BABYLON.Mesh.CAP_START:
  62013. circlePaths[0] = capPath(tessellation, 0);
  62014. circlePaths[1] = circlePaths[2].slice(0);
  62015. break;
  62016. case BABYLON.Mesh.CAP_END:
  62017. circlePaths[index] = circlePaths[index - 1].slice(0);
  62018. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62019. break;
  62020. case BABYLON.Mesh.CAP_ALL:
  62021. circlePaths[0] = capPath(tessellation, 0);
  62022. circlePaths[1] = circlePaths[2].slice(0);
  62023. circlePaths[index] = circlePaths[index - 1].slice(0);
  62024. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62025. break;
  62026. default:
  62027. break;
  62028. }
  62029. return circlePaths;
  62030. };
  62031. var path3D;
  62032. var pathArray;
  62033. if (instance) { // tube update
  62034. var arc = options.arc || instance.arc;
  62035. path3D = (instance.path3D).update(path);
  62036. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62037. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62038. instance.path3D = path3D;
  62039. instance.pathArray = pathArray;
  62040. instance.arc = arc;
  62041. instance.radius = radius;
  62042. return instance;
  62043. }
  62044. // tube creation
  62045. path3D = new BABYLON.Path3D(path);
  62046. var newPathArray = new Array();
  62047. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62048. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62049. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62050. tube.pathArray = pathArray;
  62051. tube.path3D = path3D;
  62052. tube.tessellation = tessellation;
  62053. tube.cap = cap;
  62054. tube.arc = options.arc;
  62055. tube.radius = radius;
  62056. return tube;
  62057. };
  62058. /**
  62059. * Creates a polyhedron mesh
  62060. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  62061. * * The parameter `size` (positive float, default 1) sets the polygon size
  62062. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62063. * * 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`
  62064. * * 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
  62065. * * 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)`)
  62066. * * 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
  62067. * * 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
  62068. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62069. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62070. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62071. * @param name defines the name of the mesh
  62072. * @param options defines the options used to create the mesh
  62073. * @param scene defines the hosting scene
  62074. * @returns the polyhedron mesh
  62075. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62076. */
  62077. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62078. var polyhedron = new BABYLON.Mesh(name, scene);
  62079. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62080. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62081. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62082. vertexData.applyToMesh(polyhedron, options.updatable);
  62083. return polyhedron;
  62084. };
  62085. /**
  62086. * Creates a decal mesh.
  62087. * 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
  62088. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62089. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62090. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62091. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62092. * @param name defines the name of the mesh
  62093. * @param sourceMesh defines the mesh where the decal must be applied
  62094. * @param options defines the options used to create the mesh
  62095. * @param scene defines the hosting scene
  62096. * @returns the decal mesh
  62097. * @see http://doc.babylonjs.com/how_to/decals
  62098. */
  62099. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62100. var indices = sourceMesh.getIndices();
  62101. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62102. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62103. var position = options.position || BABYLON.Vector3.Zero();
  62104. var normal = options.normal || BABYLON.Vector3.Up();
  62105. var size = options.size || BABYLON.Vector3.One();
  62106. var angle = options.angle || 0;
  62107. // Getting correct rotation
  62108. if (!normal) {
  62109. var target = new BABYLON.Vector3(0, 0, 1);
  62110. var camera = sourceMesh.getScene().activeCamera;
  62111. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62112. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62113. }
  62114. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62115. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62116. var pitch = Math.atan2(normal.y, len);
  62117. // Matrix
  62118. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62119. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62120. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62121. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62122. var vertexData = new BABYLON.VertexData();
  62123. vertexData.indices = [];
  62124. vertexData.positions = [];
  62125. vertexData.normals = [];
  62126. vertexData.uvs = [];
  62127. var currentVertexDataIndex = 0;
  62128. var extractDecalVector3 = function (indexId) {
  62129. var result = new BABYLON.PositionNormalVertex();
  62130. if (!indices || !positions || !normals) {
  62131. return result;
  62132. }
  62133. var vertexId = indices[indexId];
  62134. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62135. // Send vector to decal local world
  62136. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62137. // Get normal
  62138. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62139. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62140. return result;
  62141. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62142. var clip = function (vertices, axis) {
  62143. if (vertices.length === 0) {
  62144. return vertices;
  62145. }
  62146. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62147. var clipVertices = function (v0, v1) {
  62148. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62149. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62150. };
  62151. var result = new Array();
  62152. for (var index = 0; index < vertices.length; index += 3) {
  62153. var v1Out;
  62154. var v2Out;
  62155. var v3Out;
  62156. var total = 0;
  62157. var nV1 = null;
  62158. var nV2 = null;
  62159. var nV3 = null;
  62160. var nV4 = null;
  62161. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62162. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62163. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62164. v1Out = d1 > 0;
  62165. v2Out = d2 > 0;
  62166. v3Out = d3 > 0;
  62167. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62168. switch (total) {
  62169. case 0:
  62170. result.push(vertices[index]);
  62171. result.push(vertices[index + 1]);
  62172. result.push(vertices[index + 2]);
  62173. break;
  62174. case 1:
  62175. if (v1Out) {
  62176. nV1 = vertices[index + 1];
  62177. nV2 = vertices[index + 2];
  62178. nV3 = clipVertices(vertices[index], nV1);
  62179. nV4 = clipVertices(vertices[index], nV2);
  62180. }
  62181. if (v2Out) {
  62182. nV1 = vertices[index];
  62183. nV2 = vertices[index + 2];
  62184. nV3 = clipVertices(vertices[index + 1], nV1);
  62185. nV4 = clipVertices(vertices[index + 1], nV2);
  62186. result.push(nV3);
  62187. result.push(nV2.clone());
  62188. result.push(nV1.clone());
  62189. result.push(nV2.clone());
  62190. result.push(nV3.clone());
  62191. result.push(nV4);
  62192. break;
  62193. }
  62194. if (v3Out) {
  62195. nV1 = vertices[index];
  62196. nV2 = vertices[index + 1];
  62197. nV3 = clipVertices(vertices[index + 2], nV1);
  62198. nV4 = clipVertices(vertices[index + 2], nV2);
  62199. }
  62200. if (nV1 && nV2 && nV3 && nV4) {
  62201. result.push(nV1.clone());
  62202. result.push(nV2.clone());
  62203. result.push(nV3);
  62204. result.push(nV4);
  62205. result.push(nV3.clone());
  62206. result.push(nV2.clone());
  62207. }
  62208. break;
  62209. case 2:
  62210. if (!v1Out) {
  62211. nV1 = vertices[index].clone();
  62212. nV2 = clipVertices(nV1, vertices[index + 1]);
  62213. nV3 = clipVertices(nV1, vertices[index + 2]);
  62214. result.push(nV1);
  62215. result.push(nV2);
  62216. result.push(nV3);
  62217. }
  62218. if (!v2Out) {
  62219. nV1 = vertices[index + 1].clone();
  62220. nV2 = clipVertices(nV1, vertices[index + 2]);
  62221. nV3 = clipVertices(nV1, vertices[index]);
  62222. result.push(nV1);
  62223. result.push(nV2);
  62224. result.push(nV3);
  62225. }
  62226. if (!v3Out) {
  62227. nV1 = vertices[index + 2].clone();
  62228. nV2 = clipVertices(nV1, vertices[index]);
  62229. nV3 = clipVertices(nV1, vertices[index + 1]);
  62230. result.push(nV1);
  62231. result.push(nV2);
  62232. result.push(nV3);
  62233. }
  62234. break;
  62235. case 3:
  62236. break;
  62237. }
  62238. }
  62239. return result;
  62240. };
  62241. for (var index = 0; index < indices.length; index += 3) {
  62242. var faceVertices = new Array();
  62243. faceVertices.push(extractDecalVector3(index));
  62244. faceVertices.push(extractDecalVector3(index + 1));
  62245. faceVertices.push(extractDecalVector3(index + 2));
  62246. // Clip
  62247. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62248. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62249. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62250. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62251. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62252. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62253. if (faceVertices.length === 0) {
  62254. continue;
  62255. }
  62256. // Add UVs and get back to world
  62257. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62258. var vertex = faceVertices[vIndex];
  62259. //TODO check for Int32Array | Uint32Array | Uint16Array
  62260. vertexData.indices.push(currentVertexDataIndex);
  62261. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62262. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62263. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62264. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62265. currentVertexDataIndex++;
  62266. }
  62267. }
  62268. // Return mesh
  62269. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62270. vertexData.applyToMesh(decal);
  62271. decal.position = position.clone();
  62272. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62273. return decal;
  62274. };
  62275. // Privates
  62276. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62277. // extrusion geometry
  62278. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62279. var tangents = path3D.getTangents();
  62280. var normals = path3D.getNormals();
  62281. var binormals = path3D.getBinormals();
  62282. var distances = path3D.getDistances();
  62283. var angle = 0;
  62284. var returnScale = function () { return scale !== null ? scale : 1; };
  62285. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62286. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62287. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62288. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62289. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62290. for (var i = 0; i < curve.length; i++) {
  62291. var shapePath = new Array();
  62292. var angleStep = rotate(i, distances[i]);
  62293. var scaleRatio = scl(i, distances[i]);
  62294. for (var p = 0; p < shape.length; p++) {
  62295. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62296. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62297. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62298. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62299. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62300. shapePath[p] = rotated;
  62301. }
  62302. shapePaths[index] = shapePath;
  62303. angle += angleStep;
  62304. index++;
  62305. }
  62306. // cap
  62307. var capPath = function (shapePath) {
  62308. var pointCap = Array();
  62309. var barycenter = BABYLON.Vector3.Zero();
  62310. var i;
  62311. for (i = 0; i < shapePath.length; i++) {
  62312. barycenter.addInPlace(shapePath[i]);
  62313. }
  62314. barycenter.scaleInPlace(1.0 / shapePath.length);
  62315. for (i = 0; i < shapePath.length; i++) {
  62316. pointCap.push(barycenter);
  62317. }
  62318. return pointCap;
  62319. };
  62320. switch (cap) {
  62321. case BABYLON.Mesh.NO_CAP:
  62322. break;
  62323. case BABYLON.Mesh.CAP_START:
  62324. shapePaths[0] = capPath(shapePaths[2]);
  62325. shapePaths[1] = shapePaths[2];
  62326. break;
  62327. case BABYLON.Mesh.CAP_END:
  62328. shapePaths[index] = shapePaths[index - 1];
  62329. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62330. break;
  62331. case BABYLON.Mesh.CAP_ALL:
  62332. shapePaths[0] = capPath(shapePaths[2]);
  62333. shapePaths[1] = shapePaths[2];
  62334. shapePaths[index] = shapePaths[index - 1];
  62335. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62336. break;
  62337. default:
  62338. break;
  62339. }
  62340. return shapePaths;
  62341. };
  62342. var path3D;
  62343. var pathArray;
  62344. if (instance) { // instance update
  62345. path3D = (instance.path3D).update(curve);
  62346. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62347. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62348. return instance;
  62349. }
  62350. // extruded shape creation
  62351. path3D = new BABYLON.Path3D(curve);
  62352. var newShapePaths = new Array();
  62353. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62354. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62355. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62356. extrudedGeneric.pathArray = pathArray;
  62357. extrudedGeneric.path3D = path3D;
  62358. extrudedGeneric.cap = cap;
  62359. return extrudedGeneric;
  62360. };
  62361. return MeshBuilder;
  62362. }());
  62363. BABYLON.MeshBuilder = MeshBuilder;
  62364. })(BABYLON || (BABYLON = {}));
  62365. //# sourceMappingURL=babylon.meshBuilder.js.map
  62366. var BABYLON;
  62367. (function (BABYLON) {
  62368. /**
  62369. * Draco compression (https://google.github.io/draco/)
  62370. *
  62371. * This class wraps the Draco module.
  62372. *
  62373. * **Encoder**
  62374. *
  62375. * The encoder is not currently implemented.
  62376. *
  62377. * **Decoder**
  62378. *
  62379. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62380. *
  62381. * To update the configuration, use the following code:
  62382. * ```javascript
  62383. * BABYLON.DracoCompression.Configuration = {
  62384. * decoder: {
  62385. * wasmUrl: "<url to the WebAssembly library>",
  62386. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62387. * fallbackUrl: "<url to the fallback JavaScript library>",
  62388. * }
  62389. * };
  62390. * ```
  62391. *
  62392. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62393. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62394. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62395. *
  62396. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62397. * ```javascript
  62398. * var dracoCompression = new BABYLON.DracoCompression();
  62399. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62400. * [BABYLON.VertexBuffer.PositionKind]: 0
  62401. * });
  62402. * ```
  62403. *
  62404. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62405. */
  62406. var DracoCompression = /** @class */ (function () {
  62407. /**
  62408. * Constructor
  62409. */
  62410. function DracoCompression() {
  62411. }
  62412. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62413. /**
  62414. * Returns true if the decoder is available.
  62415. */
  62416. get: function () {
  62417. if (typeof DracoDecoderModule !== "undefined") {
  62418. return true;
  62419. }
  62420. var decoder = DracoCompression.Configuration.decoder;
  62421. if (decoder) {
  62422. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62423. return true;
  62424. }
  62425. if (decoder.fallbackUrl) {
  62426. return true;
  62427. }
  62428. }
  62429. return false;
  62430. },
  62431. enumerable: true,
  62432. configurable: true
  62433. });
  62434. /**
  62435. * Stop all async operations and release resources.
  62436. */
  62437. DracoCompression.prototype.dispose = function () {
  62438. };
  62439. /**
  62440. * Decode Draco compressed mesh data to vertex data.
  62441. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62442. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62443. * @returns A promise that resolves with the decoded vertex data
  62444. */
  62445. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62446. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62447. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62448. var module = wrappedModule.module;
  62449. var vertexData = new BABYLON.VertexData();
  62450. var buffer = new module.DecoderBuffer();
  62451. buffer.Init(dataView, dataView.byteLength);
  62452. var decoder = new module.Decoder();
  62453. var geometry;
  62454. var status;
  62455. try {
  62456. var type = decoder.GetEncodedGeometryType(buffer);
  62457. switch (type) {
  62458. case module.TRIANGULAR_MESH:
  62459. geometry = new module.Mesh();
  62460. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62461. break;
  62462. case module.POINT_CLOUD:
  62463. geometry = new module.PointCloud();
  62464. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62465. break;
  62466. default:
  62467. throw new Error("Invalid geometry type " + type);
  62468. }
  62469. if (!status.ok() || !geometry.ptr) {
  62470. throw new Error(status.error_msg());
  62471. }
  62472. var numPoints = geometry.num_points();
  62473. if (type === module.TRIANGULAR_MESH) {
  62474. var numFaces = geometry.num_faces();
  62475. var faceIndices = new module.DracoInt32Array();
  62476. try {
  62477. var indices = new Uint32Array(numFaces * 3);
  62478. for (var i = 0; i < numFaces; i++) {
  62479. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62480. var offset = i * 3;
  62481. indices[offset + 0] = faceIndices.GetValue(0);
  62482. indices[offset + 1] = faceIndices.GetValue(1);
  62483. indices[offset + 2] = faceIndices.GetValue(2);
  62484. }
  62485. vertexData.indices = indices;
  62486. }
  62487. finally {
  62488. module.destroy(faceIndices);
  62489. }
  62490. }
  62491. for (var kind in attributes) {
  62492. var uniqueId = attributes[kind];
  62493. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62494. var dracoData = new module.DracoFloat32Array();
  62495. try {
  62496. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62497. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62498. for (var i = 0; i < babylonData.length; i++) {
  62499. babylonData[i] = dracoData.GetValue(i);
  62500. }
  62501. vertexData.set(babylonData, kind);
  62502. }
  62503. finally {
  62504. module.destroy(dracoData);
  62505. }
  62506. }
  62507. }
  62508. finally {
  62509. if (geometry) {
  62510. module.destroy(geometry);
  62511. }
  62512. module.destroy(decoder);
  62513. module.destroy(buffer);
  62514. }
  62515. return vertexData;
  62516. });
  62517. };
  62518. DracoCompression._GetDecoderModule = function () {
  62519. if (!DracoCompression._DecoderModulePromise) {
  62520. var promise = null;
  62521. var config_1 = {};
  62522. if (typeof DracoDecoderModule !== "undefined") {
  62523. promise = Promise.resolve();
  62524. }
  62525. else {
  62526. var decoder = DracoCompression.Configuration.decoder;
  62527. if (decoder) {
  62528. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62529. promise = Promise.all([
  62530. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62531. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62532. config_1.wasmBinary = data;
  62533. })
  62534. ]);
  62535. }
  62536. else if (decoder.fallbackUrl) {
  62537. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62538. }
  62539. }
  62540. }
  62541. if (!promise) {
  62542. throw new Error("Draco decoder module is not available");
  62543. }
  62544. DracoCompression._DecoderModulePromise = promise.then(function () {
  62545. return new Promise(function (resolve) {
  62546. config_1.onModuleLoaded = function (decoderModule) {
  62547. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62548. resolve({ module: decoderModule });
  62549. };
  62550. DracoDecoderModule(config_1);
  62551. });
  62552. });
  62553. }
  62554. return DracoCompression._DecoderModulePromise;
  62555. };
  62556. DracoCompression._LoadScriptAsync = function (url) {
  62557. return new Promise(function (resolve, reject) {
  62558. BABYLON.Tools.LoadScript(url, function () {
  62559. resolve();
  62560. }, function (message) {
  62561. reject(new Error(message));
  62562. });
  62563. });
  62564. };
  62565. DracoCompression._LoadFileAsync = function (url) {
  62566. return new Promise(function (resolve, reject) {
  62567. BABYLON.Tools.LoadFile(url, function (data) {
  62568. resolve(data);
  62569. }, undefined, undefined, true, function (request, exception) {
  62570. reject(exception);
  62571. });
  62572. });
  62573. };
  62574. /**
  62575. * The configuration. Defaults to the following urls:
  62576. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62577. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62578. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62579. */
  62580. DracoCompression.Configuration = {
  62581. decoder: {
  62582. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62583. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62584. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62585. }
  62586. };
  62587. return DracoCompression;
  62588. }());
  62589. BABYLON.DracoCompression = DracoCompression;
  62590. })(BABYLON || (BABYLON = {}));
  62591. //# sourceMappingURL=babylon.dracoCompression.js.map
  62592. var BABYLON;
  62593. (function (BABYLON) {
  62594. var AudioEngine = /** @class */ (function () {
  62595. function AudioEngine() {
  62596. this._audioContext = null;
  62597. this._audioContextInitialized = false;
  62598. this.canUseWebAudio = false;
  62599. this.WarnedWebAudioUnsupported = false;
  62600. this.unlocked = false;
  62601. this.isMP3supported = false;
  62602. this.isOGGsupported = false;
  62603. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62604. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62605. this.canUseWebAudio = true;
  62606. }
  62607. var audioElem = document.createElement('audio');
  62608. try {
  62609. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62610. this.isMP3supported = true;
  62611. }
  62612. }
  62613. catch (e) {
  62614. // protect error during capability check.
  62615. }
  62616. try {
  62617. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62618. this.isOGGsupported = true;
  62619. }
  62620. }
  62621. catch (e) {
  62622. // protect error during capability check.
  62623. }
  62624. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62625. this._unlockiOSaudio();
  62626. }
  62627. else {
  62628. this.unlocked = true;
  62629. }
  62630. }
  62631. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62632. get: function () {
  62633. if (!this._audioContextInitialized) {
  62634. this._initializeAudioContext();
  62635. }
  62636. return this._audioContext;
  62637. },
  62638. enumerable: true,
  62639. configurable: true
  62640. });
  62641. AudioEngine.prototype._unlockiOSaudio = function () {
  62642. var _this = this;
  62643. var unlockaudio = function () {
  62644. if (!_this.audioContext) {
  62645. return;
  62646. }
  62647. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62648. var source = _this.audioContext.createBufferSource();
  62649. source.buffer = buffer;
  62650. source.connect(_this.audioContext.destination);
  62651. source.start(0);
  62652. setTimeout(function () {
  62653. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62654. _this.unlocked = true;
  62655. window.removeEventListener('touchend', unlockaudio, false);
  62656. if (_this.onAudioUnlocked) {
  62657. _this.onAudioUnlocked();
  62658. }
  62659. }
  62660. }, 0);
  62661. };
  62662. window.addEventListener('touchend', unlockaudio, false);
  62663. };
  62664. AudioEngine.prototype._initializeAudioContext = function () {
  62665. try {
  62666. if (this.canUseWebAudio) {
  62667. this._audioContext = new AudioContext();
  62668. // create a global volume gain node
  62669. this.masterGain = this._audioContext.createGain();
  62670. this.masterGain.gain.value = 1;
  62671. this.masterGain.connect(this._audioContext.destination);
  62672. this._audioContextInitialized = true;
  62673. }
  62674. }
  62675. catch (e) {
  62676. this.canUseWebAudio = false;
  62677. BABYLON.Tools.Error("Web Audio: " + e.message);
  62678. }
  62679. };
  62680. AudioEngine.prototype.dispose = function () {
  62681. if (this.canUseWebAudio && this._audioContextInitialized) {
  62682. if (this._connectedAnalyser && this._audioContext) {
  62683. this._connectedAnalyser.stopDebugCanvas();
  62684. this._connectedAnalyser.dispose();
  62685. this.masterGain.disconnect();
  62686. this.masterGain.connect(this._audioContext.destination);
  62687. this._connectedAnalyser = null;
  62688. }
  62689. this.masterGain.gain.value = 1;
  62690. }
  62691. this.WarnedWebAudioUnsupported = false;
  62692. };
  62693. AudioEngine.prototype.getGlobalVolume = function () {
  62694. if (this.canUseWebAudio && this._audioContextInitialized) {
  62695. return this.masterGain.gain.value;
  62696. }
  62697. else {
  62698. return -1;
  62699. }
  62700. };
  62701. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62702. if (this.canUseWebAudio && this._audioContextInitialized) {
  62703. this.masterGain.gain.value = newVolume;
  62704. }
  62705. };
  62706. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62707. if (this._connectedAnalyser) {
  62708. this._connectedAnalyser.stopDebugCanvas();
  62709. }
  62710. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62711. this._connectedAnalyser = analyser;
  62712. this.masterGain.disconnect();
  62713. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62714. }
  62715. };
  62716. return AudioEngine;
  62717. }());
  62718. BABYLON.AudioEngine = AudioEngine;
  62719. })(BABYLON || (BABYLON = {}));
  62720. //# sourceMappingURL=babylon.audioEngine.js.map
  62721. var BABYLON;
  62722. (function (BABYLON) {
  62723. var Sound = /** @class */ (function () {
  62724. /**
  62725. * Create a sound and attach it to a scene
  62726. * @param name Name of your sound
  62727. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62728. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62729. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62730. */
  62731. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62732. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62733. var _this = this;
  62734. this.autoplay = false;
  62735. this.loop = false;
  62736. this.useCustomAttenuation = false;
  62737. this.spatialSound = false;
  62738. this.refDistance = 1;
  62739. this.rolloffFactor = 1;
  62740. this.maxDistance = 100;
  62741. this.distanceModel = "linear";
  62742. this._panningModel = "equalpower";
  62743. this._playbackRate = 1;
  62744. this._streaming = false;
  62745. this._startTime = 0;
  62746. this._startOffset = 0;
  62747. this._position = BABYLON.Vector3.Zero();
  62748. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62749. this._volume = 1;
  62750. this._isReadyToPlay = false;
  62751. this.isPlaying = false;
  62752. this.isPaused = false;
  62753. this._isDirectional = false;
  62754. // Used if you'd like to create a directional sound.
  62755. // If not set, the sound will be omnidirectional
  62756. this._coneInnerAngle = 360;
  62757. this._coneOuterAngle = 360;
  62758. this._coneOuterGain = 0;
  62759. this._isOutputConnected = false;
  62760. this._urlType = "Unknown";
  62761. this.name = name;
  62762. this._scene = scene;
  62763. this._readyToPlayCallback = readyToPlayCallback;
  62764. // Default custom attenuation function is a linear attenuation
  62765. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62766. if (currentDistance < maxDistance) {
  62767. return currentVolume * (1 - currentDistance / maxDistance);
  62768. }
  62769. else {
  62770. return 0;
  62771. }
  62772. };
  62773. if (options) {
  62774. this.autoplay = options.autoplay || false;
  62775. this.loop = options.loop || false;
  62776. // if volume === 0, we need another way to check this option
  62777. if (options.volume !== undefined) {
  62778. this._volume = options.volume;
  62779. }
  62780. this.spatialSound = options.spatialSound || false;
  62781. this.maxDistance = options.maxDistance || 100;
  62782. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62783. this.rolloffFactor = options.rolloffFactor || 1;
  62784. this.refDistance = options.refDistance || 1;
  62785. this.distanceModel = options.distanceModel || "linear";
  62786. this._playbackRate = options.playbackRate || 1;
  62787. this._streaming = options.streaming || false;
  62788. }
  62789. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62790. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62791. this._soundGain.gain.value = this._volume;
  62792. this._inputAudioNode = this._soundGain;
  62793. this._ouputAudioNode = this._soundGain;
  62794. if (this.spatialSound) {
  62795. this._createSpatialParameters();
  62796. }
  62797. this._scene.mainSoundTrack.AddSound(this);
  62798. var validParameter = true;
  62799. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62800. if (urlOrArrayBuffer) {
  62801. try {
  62802. if (typeof (urlOrArrayBuffer) === "string")
  62803. this._urlType = "String";
  62804. if (Array.isArray(urlOrArrayBuffer))
  62805. this._urlType = "Array";
  62806. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62807. this._urlType = "ArrayBuffer";
  62808. var urls = [];
  62809. var codecSupportedFound = false;
  62810. switch (this._urlType) {
  62811. case "ArrayBuffer":
  62812. if (urlOrArrayBuffer.byteLength > 0) {
  62813. codecSupportedFound = true;
  62814. this._soundLoaded(urlOrArrayBuffer);
  62815. }
  62816. break;
  62817. case "String":
  62818. urls.push(urlOrArrayBuffer);
  62819. case "Array":
  62820. if (urls.length === 0)
  62821. urls = urlOrArrayBuffer;
  62822. // If we found a supported format, we load it immediately and stop the loop
  62823. for (var i = 0; i < urls.length; i++) {
  62824. var url = urls[i];
  62825. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62826. codecSupportedFound = true;
  62827. }
  62828. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62829. codecSupportedFound = true;
  62830. }
  62831. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62832. codecSupportedFound = true;
  62833. }
  62834. if (url.indexOf("blob:") !== -1) {
  62835. codecSupportedFound = true;
  62836. }
  62837. if (codecSupportedFound) {
  62838. // Loading sound using XHR2
  62839. if (!this._streaming) {
  62840. this._scene._loadFile(url, function (data) {
  62841. _this._soundLoaded(data);
  62842. }, undefined, true, true, function (exception) {
  62843. if (exception) {
  62844. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62845. }
  62846. BABYLON.Tools.Error("Sound creation aborted.");
  62847. _this._scene.mainSoundTrack.RemoveSound(_this);
  62848. });
  62849. }
  62850. // Streaming sound using HTML5 Audio tag
  62851. else {
  62852. this._htmlAudioElement = new Audio(url);
  62853. this._htmlAudioElement.controls = false;
  62854. this._htmlAudioElement.loop = this.loop;
  62855. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62856. this._htmlAudioElement.preload = "auto";
  62857. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62858. _this._isReadyToPlay = true;
  62859. if (_this.autoplay) {
  62860. _this.play();
  62861. }
  62862. if (_this._readyToPlayCallback) {
  62863. _this._readyToPlayCallback();
  62864. }
  62865. });
  62866. document.body.appendChild(this._htmlAudioElement);
  62867. }
  62868. break;
  62869. }
  62870. }
  62871. break;
  62872. default:
  62873. validParameter = false;
  62874. break;
  62875. }
  62876. if (!validParameter) {
  62877. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62878. }
  62879. else {
  62880. if (!codecSupportedFound) {
  62881. this._isReadyToPlay = true;
  62882. // Simulating a ready to play event to avoid breaking code path
  62883. if (this._readyToPlayCallback) {
  62884. window.setTimeout(function () {
  62885. if (_this._readyToPlayCallback) {
  62886. _this._readyToPlayCallback();
  62887. }
  62888. }, 1000);
  62889. }
  62890. }
  62891. }
  62892. }
  62893. catch (ex) {
  62894. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62895. this._scene.mainSoundTrack.RemoveSound(this);
  62896. }
  62897. }
  62898. }
  62899. else {
  62900. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62901. this._scene.mainSoundTrack.AddSound(this);
  62902. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62903. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62904. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62905. }
  62906. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62907. if (this._readyToPlayCallback) {
  62908. window.setTimeout(function () {
  62909. if (_this._readyToPlayCallback) {
  62910. _this._readyToPlayCallback();
  62911. }
  62912. }, 1000);
  62913. }
  62914. }
  62915. }
  62916. Sound.prototype.dispose = function () {
  62917. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62918. if (this.isPlaying) {
  62919. this.stop();
  62920. }
  62921. this._isReadyToPlay = false;
  62922. if (this.soundTrackId === -1) {
  62923. this._scene.mainSoundTrack.RemoveSound(this);
  62924. }
  62925. else {
  62926. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62927. }
  62928. if (this._soundGain) {
  62929. this._soundGain.disconnect();
  62930. this._soundGain = null;
  62931. }
  62932. if (this._soundPanner) {
  62933. this._soundPanner.disconnect();
  62934. this._soundPanner = null;
  62935. }
  62936. if (this._soundSource) {
  62937. this._soundSource.disconnect();
  62938. this._soundSource = null;
  62939. }
  62940. this._audioBuffer = null;
  62941. if (this._htmlAudioElement) {
  62942. this._htmlAudioElement.pause();
  62943. this._htmlAudioElement.src = "";
  62944. document.body.removeChild(this._htmlAudioElement);
  62945. }
  62946. if (this._connectedMesh && this._registerFunc) {
  62947. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62948. this._connectedMesh = null;
  62949. }
  62950. }
  62951. };
  62952. Sound.prototype.isReady = function () {
  62953. return this._isReadyToPlay;
  62954. };
  62955. Sound.prototype._soundLoaded = function (audioData) {
  62956. var _this = this;
  62957. if (!BABYLON.Engine.audioEngine.audioContext) {
  62958. return;
  62959. }
  62960. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62961. _this._audioBuffer = buffer;
  62962. _this._isReadyToPlay = true;
  62963. if (_this.autoplay) {
  62964. _this.play();
  62965. }
  62966. if (_this._readyToPlayCallback) {
  62967. _this._readyToPlayCallback();
  62968. }
  62969. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62970. };
  62971. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62972. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62973. this._audioBuffer = audioBuffer;
  62974. this._isReadyToPlay = true;
  62975. }
  62976. };
  62977. Sound.prototype.updateOptions = function (options) {
  62978. if (options) {
  62979. this.loop = options.loop || this.loop;
  62980. this.maxDistance = options.maxDistance || this.maxDistance;
  62981. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62982. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62983. this.refDistance = options.refDistance || this.refDistance;
  62984. this.distanceModel = options.distanceModel || this.distanceModel;
  62985. this._playbackRate = options.playbackRate || this._playbackRate;
  62986. this._updateSpatialParameters();
  62987. if (this.isPlaying) {
  62988. if (this._streaming) {
  62989. this._htmlAudioElement.playbackRate = this._playbackRate;
  62990. }
  62991. else {
  62992. if (this._soundSource) {
  62993. this._soundSource.playbackRate.value = this._playbackRate;
  62994. }
  62995. }
  62996. }
  62997. }
  62998. };
  62999. Sound.prototype._createSpatialParameters = function () {
  63000. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63001. if (this._scene.headphone) {
  63002. this._panningModel = "HRTF";
  63003. }
  63004. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63005. this._updateSpatialParameters();
  63006. this._soundPanner.connect(this._ouputAudioNode);
  63007. this._inputAudioNode = this._soundPanner;
  63008. }
  63009. };
  63010. Sound.prototype._updateSpatialParameters = function () {
  63011. if (this.spatialSound && this._soundPanner) {
  63012. if (this.useCustomAttenuation) {
  63013. // Tricks to disable in a way embedded Web Audio attenuation
  63014. this._soundPanner.distanceModel = "linear";
  63015. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63016. this._soundPanner.refDistance = 1;
  63017. this._soundPanner.rolloffFactor = 1;
  63018. this._soundPanner.panningModel = this._panningModel;
  63019. }
  63020. else {
  63021. this._soundPanner.distanceModel = this.distanceModel;
  63022. this._soundPanner.maxDistance = this.maxDistance;
  63023. this._soundPanner.refDistance = this.refDistance;
  63024. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63025. this._soundPanner.panningModel = this._panningModel;
  63026. }
  63027. }
  63028. };
  63029. Sound.prototype.switchPanningModelToHRTF = function () {
  63030. this._panningModel = "HRTF";
  63031. this._switchPanningModel();
  63032. };
  63033. Sound.prototype.switchPanningModelToEqualPower = function () {
  63034. this._panningModel = "equalpower";
  63035. this._switchPanningModel();
  63036. };
  63037. Sound.prototype._switchPanningModel = function () {
  63038. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63039. this._soundPanner.panningModel = this._panningModel;
  63040. }
  63041. };
  63042. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63043. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63044. if (this._isOutputConnected) {
  63045. this._ouputAudioNode.disconnect();
  63046. }
  63047. this._ouputAudioNode.connect(soundTrackAudioNode);
  63048. this._isOutputConnected = true;
  63049. }
  63050. };
  63051. /**
  63052. * Transform this sound into a directional source
  63053. * @param coneInnerAngle Size of the inner cone in degree
  63054. * @param coneOuterAngle Size of the outer cone in degree
  63055. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63056. */
  63057. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63058. if (coneOuterAngle < coneInnerAngle) {
  63059. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63060. return;
  63061. }
  63062. this._coneInnerAngle = coneInnerAngle;
  63063. this._coneOuterAngle = coneOuterAngle;
  63064. this._coneOuterGain = coneOuterGain;
  63065. this._isDirectional = true;
  63066. if (this.isPlaying && this.loop) {
  63067. this.stop();
  63068. this.play();
  63069. }
  63070. };
  63071. Sound.prototype.setPosition = function (newPosition) {
  63072. this._position = newPosition;
  63073. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63074. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63075. }
  63076. };
  63077. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63078. this._localDirection = newLocalDirection;
  63079. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63080. this._updateDirection();
  63081. }
  63082. };
  63083. Sound.prototype._updateDirection = function () {
  63084. if (!this._connectedMesh || !this._soundPanner) {
  63085. return;
  63086. }
  63087. var mat = this._connectedMesh.getWorldMatrix();
  63088. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63089. direction.normalize();
  63090. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63091. };
  63092. Sound.prototype.updateDistanceFromListener = function () {
  63093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63094. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63095. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63096. }
  63097. };
  63098. Sound.prototype.setAttenuationFunction = function (callback) {
  63099. this._customAttenuationFunction = callback;
  63100. };
  63101. /**
  63102. * Play the sound
  63103. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63104. * @param offset (optional) Start the sound setting it at a specific time
  63105. */
  63106. Sound.prototype.play = function (time, offset) {
  63107. var _this = this;
  63108. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63109. try {
  63110. if (this._startOffset < 0) {
  63111. time = -this._startOffset;
  63112. this._startOffset = 0;
  63113. }
  63114. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63115. if (!this._soundSource || !this._streamingSource) {
  63116. if (this.spatialSound && this._soundPanner) {
  63117. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63118. if (this._isDirectional) {
  63119. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63120. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63121. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63122. if (this._connectedMesh) {
  63123. this._updateDirection();
  63124. }
  63125. else {
  63126. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63127. }
  63128. }
  63129. }
  63130. }
  63131. if (this._streaming) {
  63132. if (!this._streamingSource) {
  63133. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63134. this._htmlAudioElement.onended = function () { _this._onended(); };
  63135. this._htmlAudioElement.playbackRate = this._playbackRate;
  63136. }
  63137. this._streamingSource.disconnect();
  63138. this._streamingSource.connect(this._inputAudioNode);
  63139. this._htmlAudioElement.play();
  63140. }
  63141. else {
  63142. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63143. this._soundSource.buffer = this._audioBuffer;
  63144. this._soundSource.connect(this._inputAudioNode);
  63145. this._soundSource.loop = this.loop;
  63146. this._soundSource.playbackRate.value = this._playbackRate;
  63147. this._soundSource.onended = function () { _this._onended(); };
  63148. if (this._soundSource.buffer) {
  63149. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63150. }
  63151. }
  63152. this._startTime = startTime;
  63153. this.isPlaying = true;
  63154. this.isPaused = false;
  63155. }
  63156. catch (ex) {
  63157. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63158. }
  63159. }
  63160. };
  63161. Sound.prototype._onended = function () {
  63162. this.isPlaying = false;
  63163. if (this.onended) {
  63164. this.onended();
  63165. }
  63166. };
  63167. /**
  63168. * Stop the sound
  63169. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63170. */
  63171. Sound.prototype.stop = function (time) {
  63172. if (this.isPlaying) {
  63173. if (this._streaming) {
  63174. this._htmlAudioElement.pause();
  63175. // Test needed for Firefox or it will generate an Invalid State Error
  63176. if (this._htmlAudioElement.currentTime > 0) {
  63177. this._htmlAudioElement.currentTime = 0;
  63178. }
  63179. }
  63180. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63181. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63182. this._soundSource.stop(stopTime);
  63183. this._soundSource.onended = function () { };
  63184. if (!this.isPaused) {
  63185. this._startOffset = 0;
  63186. }
  63187. }
  63188. this.isPlaying = false;
  63189. }
  63190. };
  63191. Sound.prototype.pause = function () {
  63192. if (this.isPlaying) {
  63193. this.isPaused = true;
  63194. if (this._streaming) {
  63195. this._htmlAudioElement.pause();
  63196. }
  63197. else if (BABYLON.Engine.audioEngine.audioContext) {
  63198. this.stop(0);
  63199. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63200. }
  63201. }
  63202. };
  63203. Sound.prototype.setVolume = function (newVolume, time) {
  63204. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63205. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63206. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63207. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63208. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63209. }
  63210. else {
  63211. this._soundGain.gain.value = newVolume;
  63212. }
  63213. }
  63214. this._volume = newVolume;
  63215. };
  63216. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63217. this._playbackRate = newPlaybackRate;
  63218. if (this.isPlaying) {
  63219. if (this._streaming) {
  63220. this._htmlAudioElement.playbackRate = this._playbackRate;
  63221. }
  63222. else if (this._soundSource) {
  63223. this._soundSource.playbackRate.value = this._playbackRate;
  63224. }
  63225. }
  63226. };
  63227. Sound.prototype.getVolume = function () {
  63228. return this._volume;
  63229. };
  63230. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63231. var _this = this;
  63232. if (this._connectedMesh && this._registerFunc) {
  63233. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63234. this._registerFunc = null;
  63235. }
  63236. this._connectedMesh = meshToConnectTo;
  63237. if (!this.spatialSound) {
  63238. this.spatialSound = true;
  63239. this._createSpatialParameters();
  63240. if (this.isPlaying && this.loop) {
  63241. this.stop();
  63242. this.play();
  63243. }
  63244. }
  63245. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63246. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63247. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63248. };
  63249. Sound.prototype.detachFromMesh = function () {
  63250. if (this._connectedMesh && this._registerFunc) {
  63251. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63252. this._registerFunc = null;
  63253. this._connectedMesh = null;
  63254. }
  63255. };
  63256. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63257. if (!node.getBoundingInfo) {
  63258. return;
  63259. }
  63260. var mesh = node;
  63261. var boundingInfo = mesh.getBoundingInfo();
  63262. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63264. this._updateDirection();
  63265. }
  63266. };
  63267. Sound.prototype.clone = function () {
  63268. var _this = this;
  63269. if (!this._streaming) {
  63270. var setBufferAndRun = function () {
  63271. if (_this._isReadyToPlay) {
  63272. clonedSound._audioBuffer = _this.getAudioBuffer();
  63273. clonedSound._isReadyToPlay = true;
  63274. if (clonedSound.autoplay) {
  63275. clonedSound.play();
  63276. }
  63277. }
  63278. else {
  63279. window.setTimeout(setBufferAndRun, 300);
  63280. }
  63281. };
  63282. var currentOptions = {
  63283. autoplay: this.autoplay, loop: this.loop,
  63284. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63285. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63286. refDistance: this.refDistance, distanceModel: this.distanceModel
  63287. };
  63288. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63289. if (this.useCustomAttenuation) {
  63290. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63291. }
  63292. clonedSound.setPosition(this._position);
  63293. clonedSound.setPlaybackRate(this._playbackRate);
  63294. setBufferAndRun();
  63295. return clonedSound;
  63296. }
  63297. // Can't clone a streaming sound
  63298. else {
  63299. return null;
  63300. }
  63301. };
  63302. Sound.prototype.getAudioBuffer = function () {
  63303. return this._audioBuffer;
  63304. };
  63305. Sound.prototype.serialize = function () {
  63306. var serializationObject = {
  63307. name: this.name,
  63308. url: this.name,
  63309. autoplay: this.autoplay,
  63310. loop: this.loop,
  63311. volume: this._volume,
  63312. spatialSound: this.spatialSound,
  63313. maxDistance: this.maxDistance,
  63314. rolloffFactor: this.rolloffFactor,
  63315. refDistance: this.refDistance,
  63316. distanceModel: this.distanceModel,
  63317. playbackRate: this._playbackRate,
  63318. panningModel: this._panningModel,
  63319. soundTrackId: this.soundTrackId
  63320. };
  63321. if (this.spatialSound) {
  63322. if (this._connectedMesh)
  63323. serializationObject.connectedMeshId = this._connectedMesh.id;
  63324. serializationObject.position = this._position.asArray();
  63325. serializationObject.refDistance = this.refDistance;
  63326. serializationObject.distanceModel = this.distanceModel;
  63327. serializationObject.isDirectional = this._isDirectional;
  63328. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63329. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63330. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63331. serializationObject.coneOuterGain = this._coneOuterGain;
  63332. }
  63333. return serializationObject;
  63334. };
  63335. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63336. var soundName = parsedSound.name;
  63337. var soundUrl;
  63338. if (parsedSound.url) {
  63339. soundUrl = rootUrl + parsedSound.url;
  63340. }
  63341. else {
  63342. soundUrl = rootUrl + soundName;
  63343. }
  63344. var options = {
  63345. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63346. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63347. rolloffFactor: parsedSound.rolloffFactor,
  63348. refDistance: parsedSound.refDistance,
  63349. distanceModel: parsedSound.distanceModel,
  63350. playbackRate: parsedSound.playbackRate
  63351. };
  63352. var newSound;
  63353. if (!sourceSound) {
  63354. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63355. scene._addPendingData(newSound);
  63356. }
  63357. else {
  63358. var setBufferAndRun = function () {
  63359. if (sourceSound._isReadyToPlay) {
  63360. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63361. newSound._isReadyToPlay = true;
  63362. if (newSound.autoplay) {
  63363. newSound.play();
  63364. }
  63365. }
  63366. else {
  63367. window.setTimeout(setBufferAndRun, 300);
  63368. }
  63369. };
  63370. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63371. setBufferAndRun();
  63372. }
  63373. if (parsedSound.position) {
  63374. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63375. newSound.setPosition(soundPosition);
  63376. }
  63377. if (parsedSound.isDirectional) {
  63378. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63379. if (parsedSound.localDirectionToMesh) {
  63380. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63381. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63382. }
  63383. }
  63384. if (parsedSound.connectedMeshId) {
  63385. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63386. if (connectedMesh) {
  63387. newSound.attachToMesh(connectedMesh);
  63388. }
  63389. }
  63390. return newSound;
  63391. };
  63392. return Sound;
  63393. }());
  63394. BABYLON.Sound = Sound;
  63395. })(BABYLON || (BABYLON = {}));
  63396. //# sourceMappingURL=babylon.sound.js.map
  63397. var BABYLON;
  63398. (function (BABYLON) {
  63399. var SoundTrack = /** @class */ (function () {
  63400. function SoundTrack(scene, options) {
  63401. this.id = -1;
  63402. this._isMainTrack = false;
  63403. this._isInitialized = false;
  63404. this._scene = scene;
  63405. this.soundCollection = new Array();
  63406. this._options = options;
  63407. if (!this._isMainTrack) {
  63408. this._scene.soundTracks.push(this);
  63409. this.id = this._scene.soundTracks.length - 1;
  63410. }
  63411. }
  63412. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63413. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63414. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63415. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63416. if (this._options) {
  63417. if (this._options.volume) {
  63418. this._outputAudioNode.gain.value = this._options.volume;
  63419. }
  63420. if (this._options.mainTrack) {
  63421. this._isMainTrack = this._options.mainTrack;
  63422. }
  63423. }
  63424. this._isInitialized = true;
  63425. }
  63426. };
  63427. SoundTrack.prototype.dispose = function () {
  63428. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63429. if (this._connectedAnalyser) {
  63430. this._connectedAnalyser.stopDebugCanvas();
  63431. }
  63432. while (this.soundCollection.length) {
  63433. this.soundCollection[0].dispose();
  63434. }
  63435. if (this._outputAudioNode) {
  63436. this._outputAudioNode.disconnect();
  63437. }
  63438. this._outputAudioNode = null;
  63439. }
  63440. };
  63441. SoundTrack.prototype.AddSound = function (sound) {
  63442. if (!this._isInitialized) {
  63443. this._initializeSoundTrackAudioGraph();
  63444. }
  63445. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63446. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63447. }
  63448. if (sound.soundTrackId) {
  63449. if (sound.soundTrackId === -1) {
  63450. this._scene.mainSoundTrack.RemoveSound(sound);
  63451. }
  63452. else {
  63453. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63454. }
  63455. }
  63456. this.soundCollection.push(sound);
  63457. sound.soundTrackId = this.id;
  63458. };
  63459. SoundTrack.prototype.RemoveSound = function (sound) {
  63460. var index = this.soundCollection.indexOf(sound);
  63461. if (index !== -1) {
  63462. this.soundCollection.splice(index, 1);
  63463. }
  63464. };
  63465. SoundTrack.prototype.setVolume = function (newVolume) {
  63466. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63467. this._outputAudioNode.gain.value = newVolume;
  63468. }
  63469. };
  63470. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63471. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63472. for (var i = 0; i < this.soundCollection.length; i++) {
  63473. this.soundCollection[i].switchPanningModelToHRTF();
  63474. }
  63475. }
  63476. };
  63477. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63479. for (var i = 0; i < this.soundCollection.length; i++) {
  63480. this.soundCollection[i].switchPanningModelToEqualPower();
  63481. }
  63482. }
  63483. };
  63484. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63485. if (this._connectedAnalyser) {
  63486. this._connectedAnalyser.stopDebugCanvas();
  63487. }
  63488. this._connectedAnalyser = analyser;
  63489. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63490. this._outputAudioNode.disconnect();
  63491. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63492. }
  63493. };
  63494. return SoundTrack;
  63495. }());
  63496. BABYLON.SoundTrack = SoundTrack;
  63497. })(BABYLON || (BABYLON = {}));
  63498. //# sourceMappingURL=babylon.soundtrack.js.map
  63499. var BABYLON;
  63500. (function (BABYLON) {
  63501. /**
  63502. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63503. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63504. */
  63505. var Analyser = /** @class */ (function () {
  63506. /**
  63507. * Creates a new analyser
  63508. * @param scene defines hosting scene
  63509. */
  63510. function Analyser(scene) {
  63511. /**
  63512. * Gets or sets the smoothing
  63513. * @ignorenaming
  63514. */
  63515. this.SMOOTHING = 0.75;
  63516. /**
  63517. * Gets or sets the FFT table size
  63518. * @ignorenaming
  63519. */
  63520. this.FFT_SIZE = 512;
  63521. /**
  63522. * Gets or sets the bar graph amplitude
  63523. * @ignorenaming
  63524. */
  63525. this.BARGRAPHAMPLITUDE = 256;
  63526. /**
  63527. * Gets or sets the position of the debug canvas
  63528. * @ignorenaming
  63529. */
  63530. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63531. /**
  63532. * Gets or sets the debug canvas size
  63533. * @ignorenaming
  63534. */
  63535. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63536. this._scene = scene;
  63537. this._audioEngine = BABYLON.Engine.audioEngine;
  63538. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63539. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63540. this._webAudioAnalyser.minDecibels = -140;
  63541. this._webAudioAnalyser.maxDecibels = 0;
  63542. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63543. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63544. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63545. }
  63546. }
  63547. /**
  63548. * Get the number of data values you will have to play with for the visualization
  63549. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63550. * @returns a number
  63551. */
  63552. Analyser.prototype.getFrequencyBinCount = function () {
  63553. if (this._audioEngine.canUseWebAudio) {
  63554. return this._webAudioAnalyser.frequencyBinCount;
  63555. }
  63556. else {
  63557. return 0;
  63558. }
  63559. };
  63560. /**
  63561. * Gets the current frequency data as a byte array
  63562. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63563. * @returns a Uint8Array
  63564. */
  63565. Analyser.prototype.getByteFrequencyData = function () {
  63566. if (this._audioEngine.canUseWebAudio) {
  63567. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63568. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63569. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63570. }
  63571. return this._byteFreqs;
  63572. };
  63573. /**
  63574. * Gets the current waveform as a byte array
  63575. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63576. * @returns a Uint8Array
  63577. */
  63578. Analyser.prototype.getByteTimeDomainData = function () {
  63579. if (this._audioEngine.canUseWebAudio) {
  63580. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63581. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63582. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63583. }
  63584. return this._byteTime;
  63585. };
  63586. /**
  63587. * Gets the current frequency data as a float array
  63588. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63589. * @returns a Float32Array
  63590. */
  63591. Analyser.prototype.getFloatFrequencyData = function () {
  63592. if (this._audioEngine.canUseWebAudio) {
  63593. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63594. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63595. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63596. }
  63597. return this._floatFreqs;
  63598. };
  63599. /**
  63600. * Renders the debug canvas
  63601. */
  63602. Analyser.prototype.drawDebugCanvas = function () {
  63603. var _this = this;
  63604. if (this._audioEngine.canUseWebAudio) {
  63605. if (!this._debugCanvas) {
  63606. this._debugCanvas = document.createElement("canvas");
  63607. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63608. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63609. this._debugCanvas.style.position = "absolute";
  63610. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63611. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63612. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63613. document.body.appendChild(this._debugCanvas);
  63614. this._registerFunc = function () {
  63615. _this.drawDebugCanvas();
  63616. };
  63617. this._scene.registerBeforeRender(this._registerFunc);
  63618. }
  63619. if (this._registerFunc && this._debugCanvasContext) {
  63620. var workingArray = this.getByteFrequencyData();
  63621. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63622. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63623. // Draw the frequency domain chart.
  63624. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63625. var value = workingArray[i];
  63626. var percent = value / this.BARGRAPHAMPLITUDE;
  63627. var height = this.DEBUGCANVASSIZE.height * percent;
  63628. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63629. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63630. var hue = i / this.getFrequencyBinCount() * 360;
  63631. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63632. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63633. }
  63634. }
  63635. }
  63636. };
  63637. /**
  63638. * Stops rendering the debug canvas and removes it
  63639. */
  63640. Analyser.prototype.stopDebugCanvas = function () {
  63641. if (this._debugCanvas) {
  63642. if (this._registerFunc) {
  63643. this._scene.unregisterBeforeRender(this._registerFunc);
  63644. this._registerFunc = null;
  63645. }
  63646. document.body.removeChild(this._debugCanvas);
  63647. this._debugCanvas = null;
  63648. this._debugCanvasContext = null;
  63649. }
  63650. };
  63651. /**
  63652. * Connects two audio nodes
  63653. * @param inputAudioNode defines first node to connect
  63654. * @param outputAudioNode defines second node to connect
  63655. */
  63656. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63657. if (this._audioEngine.canUseWebAudio) {
  63658. inputAudioNode.connect(this._webAudioAnalyser);
  63659. this._webAudioAnalyser.connect(outputAudioNode);
  63660. }
  63661. };
  63662. /**
  63663. * Releases all associated resources
  63664. */
  63665. Analyser.prototype.dispose = function () {
  63666. if (this._audioEngine.canUseWebAudio) {
  63667. this._webAudioAnalyser.disconnect();
  63668. }
  63669. };
  63670. return Analyser;
  63671. }());
  63672. BABYLON.Analyser = Analyser;
  63673. })(BABYLON || (BABYLON = {}));
  63674. //# sourceMappingURL=babylon.analyser.js.map
  63675. var BABYLON;
  63676. (function (BABYLON) {
  63677. var CubeTexture = /** @class */ (function (_super) {
  63678. __extends(CubeTexture, _super);
  63679. /**
  63680. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63681. * as prefiltered data.
  63682. * @param rootUrl defines the url of the texture or the root name of the six images
  63683. * @param scene defines the scene the texture is attached to
  63684. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63685. * @param noMipmap defines if mipmaps should be created or not
  63686. * @param files defines the six files to load for the different faces
  63687. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63688. * @param onError defines a callback triggered in case of error during load
  63689. * @param format defines the internal format to use for the texture once loaded
  63690. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63691. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63692. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63693. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63694. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63695. * @return the cube texture
  63696. */
  63697. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63698. if (extensions === void 0) { extensions = null; }
  63699. if (noMipmap === void 0) { noMipmap = false; }
  63700. if (files === void 0) { files = null; }
  63701. if (onLoad === void 0) { onLoad = null; }
  63702. if (onError === void 0) { onError = null; }
  63703. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63704. if (prefiltered === void 0) { prefiltered = false; }
  63705. if (forcedExtension === void 0) { forcedExtension = null; }
  63706. if (createPolynomials === void 0) { createPolynomials = false; }
  63707. if (lodScale === void 0) { lodScale = 0.8; }
  63708. if (lodOffset === void 0) { lodOffset = 0; }
  63709. var _this = _super.call(this, scene) || this;
  63710. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63711. /**
  63712. * Gets or sets the center of the bounding box associated with the cube texture
  63713. * It must define where the camera used to render the texture was set
  63714. */
  63715. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63716. _this._rotationY = 0;
  63717. /** @hidden */
  63718. _this._prefiltered = false;
  63719. _this.name = rootUrl;
  63720. _this.url = rootUrl;
  63721. _this._noMipmap = noMipmap;
  63722. _this.hasAlpha = false;
  63723. _this._format = format;
  63724. _this.isCube = true;
  63725. _this._textureMatrix = BABYLON.Matrix.Identity();
  63726. _this._createPolynomials = createPolynomials;
  63727. if (!rootUrl && !files) {
  63728. return _this;
  63729. }
  63730. var lastDot = rootUrl.lastIndexOf(".");
  63731. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63732. var isDDS = (extension === ".dds");
  63733. var isEnv = (extension === ".env");
  63734. if (isEnv) {
  63735. _this.gammaSpace = false;
  63736. _this._prefiltered = false;
  63737. }
  63738. else {
  63739. _this._prefiltered = prefiltered;
  63740. if (prefiltered) {
  63741. _this.gammaSpace = false;
  63742. }
  63743. }
  63744. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63745. if (!files) {
  63746. if (!isEnv && !isDDS && !extensions) {
  63747. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63748. }
  63749. files = [];
  63750. if (extensions) {
  63751. for (var index = 0; index < extensions.length; index++) {
  63752. files.push(rootUrl + extensions[index]);
  63753. }
  63754. }
  63755. }
  63756. _this._files = files;
  63757. if (!_this._texture) {
  63758. if (!scene.useDelayedTextureLoading) {
  63759. if (prefiltered) {
  63760. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63761. }
  63762. else {
  63763. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63764. }
  63765. }
  63766. else {
  63767. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63768. }
  63769. }
  63770. else if (onLoad) {
  63771. if (_this._texture.isReady) {
  63772. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63773. }
  63774. else {
  63775. _this._texture.onLoadedObservable.add(onLoad);
  63776. }
  63777. }
  63778. return _this;
  63779. }
  63780. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63781. get: function () {
  63782. return this._boundingBoxSize;
  63783. },
  63784. /**
  63785. * Gets or sets the size of the bounding box associated with the cube texture
  63786. * When defined, the cubemap will switch to local mode
  63787. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63788. * @example https://www.babylonjs-playground.com/#RNASML
  63789. */
  63790. set: function (value) {
  63791. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63792. return;
  63793. }
  63794. this._boundingBoxSize = value;
  63795. var scene = this.getScene();
  63796. if (scene) {
  63797. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63798. }
  63799. },
  63800. enumerable: true,
  63801. configurable: true
  63802. });
  63803. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63804. /**
  63805. * Gets texture matrix rotation angle around Y axis radians.
  63806. */
  63807. get: function () {
  63808. return this._rotationY;
  63809. },
  63810. /**
  63811. * Sets texture matrix rotation angle around Y axis in radians.
  63812. */
  63813. set: function (value) {
  63814. this._rotationY = value;
  63815. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63816. },
  63817. enumerable: true,
  63818. configurable: true
  63819. });
  63820. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63821. var rootUrlKey = "";
  63822. files.forEach(function (url) { return rootUrlKey += url; });
  63823. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63824. };
  63825. /**
  63826. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63827. * @param url defines the url of the prefiltered texture
  63828. * @param scene defines the scene the texture is attached to
  63829. * @param forcedExtension defines the extension of the file if different from the url
  63830. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63831. * @return the prefiltered texture
  63832. */
  63833. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63834. if (forcedExtension === void 0) { forcedExtension = null; }
  63835. if (createPolynomials === void 0) { createPolynomials = true; }
  63836. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63837. };
  63838. // Methods
  63839. CubeTexture.prototype.delayLoad = function () {
  63840. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63841. return;
  63842. }
  63843. var scene = this.getScene();
  63844. if (!scene) {
  63845. return;
  63846. }
  63847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63848. this._texture = this._getFromCache(this.url, this._noMipmap);
  63849. if (!this._texture) {
  63850. if (this._prefiltered) {
  63851. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63852. }
  63853. else {
  63854. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63855. }
  63856. }
  63857. };
  63858. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63859. return this._textureMatrix;
  63860. };
  63861. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63862. this._textureMatrix = value;
  63863. };
  63864. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63865. var texture = BABYLON.SerializationHelper.Parse(function () {
  63866. var prefiltered = false;
  63867. if (parsedTexture.prefiltered) {
  63868. prefiltered = parsedTexture.prefiltered;
  63869. }
  63870. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63871. }, parsedTexture, scene);
  63872. // Local Cubemaps
  63873. if (parsedTexture.boundingBoxPosition) {
  63874. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63875. }
  63876. if (parsedTexture.boundingBoxSize) {
  63877. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63878. }
  63879. // Animations
  63880. if (parsedTexture.animations) {
  63881. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63882. var parsedAnimation = parsedTexture.animations[animationIndex];
  63883. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63884. }
  63885. }
  63886. return texture;
  63887. };
  63888. CubeTexture.prototype.clone = function () {
  63889. var _this = this;
  63890. return BABYLON.SerializationHelper.Clone(function () {
  63891. var scene = _this.getScene();
  63892. if (!scene) {
  63893. return _this;
  63894. }
  63895. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63896. }, this);
  63897. };
  63898. __decorate([
  63899. BABYLON.serialize("rotationY")
  63900. ], CubeTexture.prototype, "_rotationY", void 0);
  63901. return CubeTexture;
  63902. }(BABYLON.BaseTexture));
  63903. BABYLON.CubeTexture = CubeTexture;
  63904. })(BABYLON || (BABYLON = {}));
  63905. //# sourceMappingURL=babylon.cubeTexture.js.map
  63906. var BABYLON;
  63907. (function (BABYLON) {
  63908. var RenderTargetTexture = /** @class */ (function (_super) {
  63909. __extends(RenderTargetTexture, _super);
  63910. /**
  63911. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63912. * or used a shadow, depth texture...
  63913. * @param name The friendly name of the texture
  63914. * @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)
  63915. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63916. * @param generateMipMaps True if mip maps need to be generated after render.
  63917. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63918. * @param type The type of the buffer in the RTT (int, half float, float...)
  63919. * @param isCube True if a cube texture needs to be created
  63920. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63921. * @param generateDepthBuffer True to generate a depth buffer
  63922. * @param generateStencilBuffer True to generate a stencil buffer
  63923. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63924. */
  63925. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63926. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63927. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63928. if (isCube === void 0) { isCube = false; }
  63929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63930. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63931. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63932. if (isMulti === void 0) { isMulti = false; }
  63933. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63934. _this.isCube = isCube;
  63935. /**
  63936. * Use this list to define the list of mesh you want to render.
  63937. */
  63938. _this.renderList = new Array();
  63939. _this.renderParticles = true;
  63940. _this.renderSprites = false;
  63941. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63942. _this.ignoreCameraViewport = false;
  63943. // Events
  63944. /**
  63945. * An event triggered when the texture is unbind.
  63946. */
  63947. _this.onBeforeBindObservable = new BABYLON.Observable();
  63948. /**
  63949. * An event triggered when the texture is unbind.
  63950. */
  63951. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63952. /**
  63953. * An event triggered before rendering the texture
  63954. */
  63955. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63956. /**
  63957. * An event triggered after rendering the texture
  63958. */
  63959. _this.onAfterRenderObservable = new BABYLON.Observable();
  63960. /**
  63961. * An event triggered after the texture clear
  63962. */
  63963. _this.onClearObservable = new BABYLON.Observable();
  63964. _this._currentRefreshId = -1;
  63965. _this._refreshRate = 1;
  63966. _this._samples = 1;
  63967. /**
  63968. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63969. * It must define where the camera used to render the texture is set
  63970. */
  63971. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63972. scene = _this.getScene();
  63973. if (!scene) {
  63974. return _this;
  63975. }
  63976. _this._engine = scene.getEngine();
  63977. _this.name = name;
  63978. _this.isRenderTarget = true;
  63979. _this._initialSizeParameter = size;
  63980. _this._processSizeParameter(size);
  63981. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63982. });
  63983. _this._generateMipMaps = generateMipMaps ? true : false;
  63984. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63985. // Rendering groups
  63986. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63987. if (isMulti) {
  63988. return _this;
  63989. }
  63990. _this._renderTargetOptions = {
  63991. generateMipMaps: generateMipMaps,
  63992. type: type,
  63993. samplingMode: samplingMode,
  63994. generateDepthBuffer: generateDepthBuffer,
  63995. generateStencilBuffer: generateStencilBuffer
  63996. };
  63997. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63998. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63999. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64000. }
  64001. if (isCube) {
  64002. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  64003. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  64004. _this._textureMatrix = BABYLON.Matrix.Identity();
  64005. }
  64006. else {
  64007. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  64008. }
  64009. return _this;
  64010. }
  64011. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  64012. get: function () {
  64013. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  64019. get: function () {
  64020. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64026. get: function () {
  64027. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64033. set: function (callback) {
  64034. if (this._onAfterUnbindObserver) {
  64035. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64036. }
  64037. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64038. },
  64039. enumerable: true,
  64040. configurable: true
  64041. });
  64042. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64043. set: function (callback) {
  64044. if (this._onBeforeRenderObserver) {
  64045. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64046. }
  64047. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64053. set: function (callback) {
  64054. if (this._onAfterRenderObserver) {
  64055. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64056. }
  64057. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64058. },
  64059. enumerable: true,
  64060. configurable: true
  64061. });
  64062. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64063. set: function (callback) {
  64064. if (this._onClearObserver) {
  64065. this.onClearObservable.remove(this._onClearObserver);
  64066. }
  64067. this._onClearObserver = this.onClearObservable.add(callback);
  64068. },
  64069. enumerable: true,
  64070. configurable: true
  64071. });
  64072. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64073. get: function () {
  64074. return this._renderTargetOptions;
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. RenderTargetTexture.prototype._onRatioRescale = function () {
  64080. if (this._sizeRatio) {
  64081. this.resize(this._initialSizeParameter);
  64082. }
  64083. };
  64084. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64085. get: function () {
  64086. return this._boundingBoxSize;
  64087. },
  64088. /**
  64089. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64090. * When defined, the cubemap will switch to local mode
  64091. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64092. * @example https://www.babylonjs-playground.com/#RNASML
  64093. */
  64094. set: function (value) {
  64095. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64096. return;
  64097. }
  64098. this._boundingBoxSize = value;
  64099. var scene = this.getScene();
  64100. if (scene) {
  64101. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64102. }
  64103. },
  64104. enumerable: true,
  64105. configurable: true
  64106. });
  64107. /**
  64108. * Creates a depth stencil texture.
  64109. * This is only available in WebGL 2 or with the depth texture extension available.
  64110. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64111. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64112. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64113. */
  64114. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64115. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64116. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64117. if (generateStencil === void 0) { generateStencil = false; }
  64118. if (!this.getScene()) {
  64119. return;
  64120. }
  64121. var engine = this.getScene().getEngine();
  64122. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64123. bilinearFiltering: bilinearFiltering,
  64124. comparisonFunction: comparisonFunction,
  64125. generateStencil: generateStencil,
  64126. isCube: this.isCube
  64127. });
  64128. engine.setFrameBufferDepthStencilTexture(this);
  64129. };
  64130. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64131. if (size.ratio) {
  64132. this._sizeRatio = size.ratio;
  64133. this._size = {
  64134. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64135. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64136. };
  64137. }
  64138. else {
  64139. this._size = size;
  64140. }
  64141. };
  64142. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64143. get: function () {
  64144. return this._samples;
  64145. },
  64146. set: function (value) {
  64147. if (this._samples === value) {
  64148. return;
  64149. }
  64150. var scene = this.getScene();
  64151. if (!scene) {
  64152. return;
  64153. }
  64154. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64155. },
  64156. enumerable: true,
  64157. configurable: true
  64158. });
  64159. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64160. this._currentRefreshId = -1;
  64161. };
  64162. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64163. get: function () {
  64164. return this._refreshRate;
  64165. },
  64166. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64167. set: function (value) {
  64168. this._refreshRate = value;
  64169. this.resetRefreshCounter();
  64170. },
  64171. enumerable: true,
  64172. configurable: true
  64173. });
  64174. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64175. if (!this._postProcessManager) {
  64176. var scene = this.getScene();
  64177. if (!scene) {
  64178. return;
  64179. }
  64180. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64181. this._postProcesses = new Array();
  64182. }
  64183. this._postProcesses.push(postProcess);
  64184. this._postProcesses[0].autoClear = false;
  64185. };
  64186. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64187. if (!this._postProcesses) {
  64188. return;
  64189. }
  64190. if (dispose) {
  64191. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64192. var postProcess = _a[_i];
  64193. postProcess.dispose();
  64194. }
  64195. }
  64196. this._postProcesses = [];
  64197. };
  64198. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64199. if (!this._postProcesses) {
  64200. return;
  64201. }
  64202. var index = this._postProcesses.indexOf(postProcess);
  64203. if (index === -1) {
  64204. return;
  64205. }
  64206. this._postProcesses.splice(index, 1);
  64207. if (this._postProcesses.length > 0) {
  64208. this._postProcesses[0].autoClear = false;
  64209. }
  64210. };
  64211. RenderTargetTexture.prototype._shouldRender = function () {
  64212. if (this._currentRefreshId === -1) { // At least render once
  64213. this._currentRefreshId = 1;
  64214. return true;
  64215. }
  64216. if (this.refreshRate === this._currentRefreshId) {
  64217. this._currentRefreshId = 1;
  64218. return true;
  64219. }
  64220. this._currentRefreshId++;
  64221. return false;
  64222. };
  64223. RenderTargetTexture.prototype.getRenderSize = function () {
  64224. if (this._size.width) {
  64225. return this._size.width;
  64226. }
  64227. return this._size;
  64228. };
  64229. RenderTargetTexture.prototype.getRenderWidth = function () {
  64230. if (this._size.width) {
  64231. return this._size.width;
  64232. }
  64233. return this._size;
  64234. };
  64235. RenderTargetTexture.prototype.getRenderHeight = function () {
  64236. if (this._size.width) {
  64237. return this._size.height;
  64238. }
  64239. return this._size;
  64240. };
  64241. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64242. get: function () {
  64243. return true;
  64244. },
  64245. enumerable: true,
  64246. configurable: true
  64247. });
  64248. RenderTargetTexture.prototype.scale = function (ratio) {
  64249. var newSize = this.getRenderSize() * ratio;
  64250. this.resize(newSize);
  64251. };
  64252. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64253. if (this.isCube) {
  64254. return this._textureMatrix;
  64255. }
  64256. return _super.prototype.getReflectionTextureMatrix.call(this);
  64257. };
  64258. RenderTargetTexture.prototype.resize = function (size) {
  64259. this.releaseInternalTexture();
  64260. var scene = this.getScene();
  64261. if (!scene) {
  64262. return;
  64263. }
  64264. this._processSizeParameter(size);
  64265. if (this.isCube) {
  64266. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64267. }
  64268. else {
  64269. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64270. }
  64271. };
  64272. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64273. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64274. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64275. var scene = this.getScene();
  64276. if (!scene) {
  64277. return;
  64278. }
  64279. var engine = scene.getEngine();
  64280. if (this.useCameraPostProcesses !== undefined) {
  64281. useCameraPostProcess = this.useCameraPostProcesses;
  64282. }
  64283. if (this._waitingRenderList) {
  64284. this.renderList = [];
  64285. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64286. var id = this._waitingRenderList[index];
  64287. var mesh_1 = scene.getMeshByID(id);
  64288. if (mesh_1) {
  64289. this.renderList.push(mesh_1);
  64290. }
  64291. }
  64292. delete this._waitingRenderList;
  64293. }
  64294. // Is predicate defined?
  64295. if (this.renderListPredicate) {
  64296. if (this.renderList) {
  64297. this.renderList.splice(0); // Clear previous renderList
  64298. }
  64299. else {
  64300. this.renderList = [];
  64301. }
  64302. var scene = this.getScene();
  64303. if (!scene) {
  64304. return;
  64305. }
  64306. var sceneMeshes = scene.meshes;
  64307. for (var index = 0; index < sceneMeshes.length; index++) {
  64308. var mesh = sceneMeshes[index];
  64309. if (this.renderListPredicate(mesh)) {
  64310. this.renderList.push(mesh);
  64311. }
  64312. }
  64313. }
  64314. this.onBeforeBindObservable.notifyObservers(this);
  64315. // Set custom projection.
  64316. // Needs to be before binding to prevent changing the aspect ratio.
  64317. var camera;
  64318. if (this.activeCamera) {
  64319. camera = this.activeCamera;
  64320. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64321. if (this.activeCamera !== scene.activeCamera) {
  64322. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64323. }
  64324. }
  64325. else {
  64326. camera = scene.activeCamera;
  64327. if (camera) {
  64328. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64329. }
  64330. }
  64331. // Prepare renderingManager
  64332. this._renderingManager.reset();
  64333. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64334. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64335. var sceneRenderId = scene.getRenderId();
  64336. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64337. var mesh = currentRenderList[meshIndex];
  64338. if (mesh) {
  64339. if (!mesh.isReady(this.refreshRate === 0)) {
  64340. this.resetRefreshCounter();
  64341. continue;
  64342. }
  64343. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64344. var isMasked = void 0;
  64345. if (!this.renderList && camera) {
  64346. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64347. }
  64348. else {
  64349. isMasked = false;
  64350. }
  64351. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64352. mesh._activate(sceneRenderId);
  64353. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64354. var subMesh = mesh.subMeshes[subIndex];
  64355. scene._activeIndices.addCount(subMesh.indexCount, false);
  64356. this._renderingManager.dispatch(subMesh, mesh);
  64357. }
  64358. }
  64359. }
  64360. }
  64361. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64362. var particleSystem = scene.particleSystems[particleIndex];
  64363. var emitter = particleSystem.emitter;
  64364. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64365. continue;
  64366. }
  64367. if (currentRenderList.indexOf(emitter) >= 0) {
  64368. this._renderingManager.dispatchParticles(particleSystem);
  64369. }
  64370. }
  64371. if (this.isCube) {
  64372. for (var face = 0; face < 6; face++) {
  64373. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64374. scene.incrementRenderId();
  64375. scene.resetCachedMaterial();
  64376. }
  64377. }
  64378. else {
  64379. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64380. }
  64381. this.onAfterUnbindObservable.notifyObservers(this);
  64382. if (scene.activeCamera) {
  64383. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64384. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64385. }
  64386. engine.setViewport(scene.activeCamera.viewport);
  64387. }
  64388. scene.resetCachedMaterial();
  64389. };
  64390. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64391. var minimum = 128;
  64392. var x = renderDimension * scale;
  64393. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64394. // Ensure we don't exceed the render dimension (while staying POT)
  64395. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64396. };
  64397. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64398. var _this = this;
  64399. if (!this._texture) {
  64400. return;
  64401. }
  64402. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64403. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64404. });
  64405. };
  64406. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64407. var scene = this.getScene();
  64408. if (!scene) {
  64409. return;
  64410. }
  64411. var engine = scene.getEngine();
  64412. if (!this._texture) {
  64413. return;
  64414. }
  64415. // Bind
  64416. if (this._postProcessManager) {
  64417. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64418. }
  64419. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64420. if (this._texture) {
  64421. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64422. }
  64423. }
  64424. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64425. // Clear
  64426. if (this.onClearObservable.hasObservers()) {
  64427. this.onClearObservable.notifyObservers(engine);
  64428. }
  64429. else {
  64430. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64431. }
  64432. if (!this._doNotChangeAspectRatio) {
  64433. scene.updateTransformMatrix(true);
  64434. }
  64435. // Render
  64436. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64437. if (this._postProcessManager) {
  64438. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64439. }
  64440. else if (useCameraPostProcess) {
  64441. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64442. }
  64443. if (!this._doNotChangeAspectRatio) {
  64444. scene.updateTransformMatrix(true);
  64445. }
  64446. // Dump ?
  64447. if (dumpForDebug) {
  64448. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64449. }
  64450. // Unbind
  64451. if (!this.isCube || faceIndex === 5) {
  64452. if (this.isCube) {
  64453. if (faceIndex === 5) {
  64454. engine.generateMipMapsForCubemap(this._texture);
  64455. }
  64456. }
  64457. this.unbindFrameBuffer(engine, faceIndex);
  64458. }
  64459. else {
  64460. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64461. }
  64462. };
  64463. /**
  64464. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64465. * This allowed control for front to back rendering or reversly depending of the special needs.
  64466. *
  64467. * @param renderingGroupId The rendering group id corresponding to its index
  64468. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64469. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64470. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64471. */
  64472. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64473. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64474. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64475. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64476. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64477. };
  64478. /**
  64479. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64480. *
  64481. * @param renderingGroupId The rendering group id corresponding to its index
  64482. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64483. */
  64484. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64485. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64486. };
  64487. RenderTargetTexture.prototype.clone = function () {
  64488. var textureSize = this.getSize();
  64489. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64490. // Base texture
  64491. newTexture.hasAlpha = this.hasAlpha;
  64492. newTexture.level = this.level;
  64493. // RenderTarget Texture
  64494. newTexture.coordinatesMode = this.coordinatesMode;
  64495. if (this.renderList) {
  64496. newTexture.renderList = this.renderList.slice(0);
  64497. }
  64498. return newTexture;
  64499. };
  64500. RenderTargetTexture.prototype.serialize = function () {
  64501. if (!this.name) {
  64502. return null;
  64503. }
  64504. var serializationObject = _super.prototype.serialize.call(this);
  64505. serializationObject.renderTargetSize = this.getRenderSize();
  64506. serializationObject.renderList = [];
  64507. if (this.renderList) {
  64508. for (var index = 0; index < this.renderList.length; index++) {
  64509. serializationObject.renderList.push(this.renderList[index].id);
  64510. }
  64511. }
  64512. return serializationObject;
  64513. };
  64514. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64515. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64516. var objBuffer = this.getInternalTexture();
  64517. var scene = this.getScene();
  64518. if (objBuffer && scene) {
  64519. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64520. }
  64521. };
  64522. RenderTargetTexture.prototype.dispose = function () {
  64523. if (this._postProcessManager) {
  64524. this._postProcessManager.dispose();
  64525. this._postProcessManager = null;
  64526. }
  64527. this.clearPostProcesses(true);
  64528. if (this._resizeObserver) {
  64529. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64530. this._resizeObserver = null;
  64531. }
  64532. this.renderList = null;
  64533. // Remove from custom render targets
  64534. var scene = this.getScene();
  64535. if (!scene) {
  64536. return;
  64537. }
  64538. var index = scene.customRenderTargets.indexOf(this);
  64539. if (index >= 0) {
  64540. scene.customRenderTargets.splice(index, 1);
  64541. }
  64542. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64543. var camera = _a[_i];
  64544. index = camera.customRenderTargets.indexOf(this);
  64545. if (index >= 0) {
  64546. camera.customRenderTargets.splice(index, 1);
  64547. }
  64548. }
  64549. _super.prototype.dispose.call(this);
  64550. };
  64551. RenderTargetTexture.prototype._rebuild = function () {
  64552. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64553. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64554. }
  64555. if (this._postProcessManager) {
  64556. this._postProcessManager._rebuild();
  64557. }
  64558. };
  64559. /**
  64560. * Clear the info related to rendering groups preventing retention point in material dispose.
  64561. */
  64562. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64563. if (this._renderingManager) {
  64564. this._renderingManager.freeRenderingGroups();
  64565. }
  64566. };
  64567. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64568. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64569. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64570. return RenderTargetTexture;
  64571. }(BABYLON.Texture));
  64572. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64573. })(BABYLON || (BABYLON = {}));
  64574. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64575. var BABYLON;
  64576. (function (BABYLON) {
  64577. ;
  64578. var MultiRenderTarget = /** @class */ (function (_super) {
  64579. __extends(MultiRenderTarget, _super);
  64580. function MultiRenderTarget(name, size, count, scene, options) {
  64581. var _this = this;
  64582. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64583. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64584. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64585. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64586. _this._engine = scene.getEngine();
  64587. if (!_this.isSupported) {
  64588. _this.dispose();
  64589. return;
  64590. }
  64591. var types = [];
  64592. var samplingModes = [];
  64593. for (var i = 0; i < count; i++) {
  64594. if (options && options.types && options.types[i] !== undefined) {
  64595. types.push(options.types[i]);
  64596. }
  64597. else {
  64598. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64599. }
  64600. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64601. samplingModes.push(options.samplingModes[i]);
  64602. }
  64603. else {
  64604. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64605. }
  64606. }
  64607. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64608. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64609. _this._size = size;
  64610. _this._multiRenderTargetOptions = {
  64611. samplingModes: samplingModes,
  64612. generateMipMaps: generateMipMaps,
  64613. generateDepthBuffer: generateDepthBuffer,
  64614. generateStencilBuffer: generateStencilBuffer,
  64615. generateDepthTexture: generateDepthTexture,
  64616. types: types,
  64617. textureCount: count
  64618. };
  64619. _this._createInternalTextures();
  64620. _this._createTextures();
  64621. return _this;
  64622. }
  64623. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64624. get: function () {
  64625. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64626. },
  64627. enumerable: true,
  64628. configurable: true
  64629. });
  64630. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64631. get: function () {
  64632. return this._textures;
  64633. },
  64634. enumerable: true,
  64635. configurable: true
  64636. });
  64637. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64638. get: function () {
  64639. return this._textures[this._textures.length - 1];
  64640. },
  64641. enumerable: true,
  64642. configurable: true
  64643. });
  64644. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64645. set: function (wrap) {
  64646. if (this._textures) {
  64647. for (var i = 0; i < this._textures.length; i++) {
  64648. this._textures[i].wrapU = wrap;
  64649. }
  64650. }
  64651. },
  64652. enumerable: true,
  64653. configurable: true
  64654. });
  64655. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64656. set: function (wrap) {
  64657. if (this._textures) {
  64658. for (var i = 0; i < this._textures.length; i++) {
  64659. this._textures[i].wrapV = wrap;
  64660. }
  64661. }
  64662. },
  64663. enumerable: true,
  64664. configurable: true
  64665. });
  64666. MultiRenderTarget.prototype._rebuild = function () {
  64667. this.releaseInternalTextures();
  64668. this._createInternalTextures();
  64669. for (var i = 0; i < this._internalTextures.length; i++) {
  64670. var texture = this._textures[i];
  64671. texture._texture = this._internalTextures[i];
  64672. }
  64673. // Keeps references to frame buffer and stencil/depth buffer
  64674. this._texture = this._internalTextures[0];
  64675. };
  64676. MultiRenderTarget.prototype._createInternalTextures = function () {
  64677. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64678. };
  64679. MultiRenderTarget.prototype._createTextures = function () {
  64680. this._textures = [];
  64681. for (var i = 0; i < this._internalTextures.length; i++) {
  64682. var texture = new BABYLON.Texture(null, this.getScene());
  64683. texture._texture = this._internalTextures[i];
  64684. this._textures.push(texture);
  64685. }
  64686. // Keeps references to frame buffer and stencil/depth buffer
  64687. this._texture = this._internalTextures[0];
  64688. };
  64689. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64690. get: function () {
  64691. return this._samples;
  64692. },
  64693. set: function (value) {
  64694. if (this._samples === value) {
  64695. return;
  64696. }
  64697. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64698. },
  64699. enumerable: true,
  64700. configurable: true
  64701. });
  64702. MultiRenderTarget.prototype.resize = function (size) {
  64703. this.releaseInternalTextures();
  64704. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64705. this._createInternalTextures();
  64706. };
  64707. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64708. var _this = this;
  64709. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64710. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64711. });
  64712. };
  64713. MultiRenderTarget.prototype.dispose = function () {
  64714. this.releaseInternalTextures();
  64715. _super.prototype.dispose.call(this);
  64716. };
  64717. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64718. if (!this._internalTextures) {
  64719. return;
  64720. }
  64721. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64722. if (this._internalTextures[i] !== undefined) {
  64723. this._internalTextures[i].dispose();
  64724. this._internalTextures.splice(i, 1);
  64725. }
  64726. }
  64727. };
  64728. return MultiRenderTarget;
  64729. }(BABYLON.RenderTargetTexture));
  64730. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64731. })(BABYLON || (BABYLON = {}));
  64732. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64733. var BABYLON;
  64734. (function (BABYLON) {
  64735. var MirrorTexture = /** @class */ (function (_super) {
  64736. __extends(MirrorTexture, _super);
  64737. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64738. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64740. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64741. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64742. _this.scene = scene;
  64743. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64744. _this._transformMatrix = BABYLON.Matrix.Zero();
  64745. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64746. _this._adaptiveBlurKernel = 0;
  64747. _this._blurKernelX = 0;
  64748. _this._blurKernelY = 0;
  64749. _this._blurRatio = 1.0;
  64750. _this.ignoreCameraViewport = true;
  64751. _this._updateGammaSpace();
  64752. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64753. _this._updateGammaSpace;
  64754. });
  64755. _this.onBeforeRenderObservable.add(function () {
  64756. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64757. _this._savedViewMatrix = scene.getViewMatrix();
  64758. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64759. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64760. scene.clipPlane = _this.mirrorPlane;
  64761. scene.getEngine().cullBackFaces = false;
  64762. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64763. });
  64764. _this.onAfterRenderObservable.add(function () {
  64765. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64766. scene.getEngine().cullBackFaces = true;
  64767. scene._mirroredCameraPosition = null;
  64768. delete scene.clipPlane;
  64769. });
  64770. return _this;
  64771. }
  64772. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64773. get: function () {
  64774. return this._blurRatio;
  64775. },
  64776. set: function (value) {
  64777. if (this._blurRatio === value) {
  64778. return;
  64779. }
  64780. this._blurRatio = value;
  64781. this._preparePostProcesses();
  64782. },
  64783. enumerable: true,
  64784. configurable: true
  64785. });
  64786. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64787. set: function (value) {
  64788. this._adaptiveBlurKernel = value;
  64789. this._autoComputeBlurKernel();
  64790. },
  64791. enumerable: true,
  64792. configurable: true
  64793. });
  64794. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64795. set: function (value) {
  64796. this.blurKernelX = value;
  64797. this.blurKernelY = value;
  64798. },
  64799. enumerable: true,
  64800. configurable: true
  64801. });
  64802. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64803. get: function () {
  64804. return this._blurKernelX;
  64805. },
  64806. set: function (value) {
  64807. if (this._blurKernelX === value) {
  64808. return;
  64809. }
  64810. this._blurKernelX = value;
  64811. this._preparePostProcesses();
  64812. },
  64813. enumerable: true,
  64814. configurable: true
  64815. });
  64816. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64817. get: function () {
  64818. return this._blurKernelY;
  64819. },
  64820. set: function (value) {
  64821. if (this._blurKernelY === value) {
  64822. return;
  64823. }
  64824. this._blurKernelY = value;
  64825. this._preparePostProcesses();
  64826. },
  64827. enumerable: true,
  64828. configurable: true
  64829. });
  64830. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64831. var engine = this.getScene().getEngine();
  64832. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64833. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64834. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64835. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64836. };
  64837. MirrorTexture.prototype._onRatioRescale = function () {
  64838. if (this._sizeRatio) {
  64839. this.resize(this._initialSizeParameter);
  64840. if (!this._adaptiveBlurKernel) {
  64841. this._preparePostProcesses();
  64842. }
  64843. }
  64844. if (this._adaptiveBlurKernel) {
  64845. this._autoComputeBlurKernel();
  64846. }
  64847. };
  64848. MirrorTexture.prototype._updateGammaSpace = function () {
  64849. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64850. };
  64851. MirrorTexture.prototype._preparePostProcesses = function () {
  64852. this.clearPostProcesses(true);
  64853. if (this._blurKernelX && this._blurKernelY) {
  64854. var engine = this.getScene().getEngine();
  64855. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64856. 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);
  64857. this._blurX.autoClear = false;
  64858. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64859. this._blurX.inputTexture = this._texture;
  64860. }
  64861. else {
  64862. this._blurX.alwaysForcePOT = true;
  64863. }
  64864. 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);
  64865. this._blurY.autoClear = false;
  64866. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64867. this.addPostProcess(this._blurX);
  64868. this.addPostProcess(this._blurY);
  64869. }
  64870. else {
  64871. if (this._blurY) {
  64872. this.removePostProcess(this._blurY);
  64873. this._blurY.dispose();
  64874. this._blurY = null;
  64875. }
  64876. if (this._blurX) {
  64877. this.removePostProcess(this._blurX);
  64878. this._blurX.dispose();
  64879. this._blurX = null;
  64880. }
  64881. }
  64882. };
  64883. MirrorTexture.prototype.clone = function () {
  64884. var scene = this.getScene();
  64885. if (!scene) {
  64886. return this;
  64887. }
  64888. var textureSize = this.getSize();
  64889. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64890. // Base texture
  64891. newTexture.hasAlpha = this.hasAlpha;
  64892. newTexture.level = this.level;
  64893. // Mirror Texture
  64894. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64895. if (this.renderList) {
  64896. newTexture.renderList = this.renderList.slice(0);
  64897. }
  64898. return newTexture;
  64899. };
  64900. MirrorTexture.prototype.serialize = function () {
  64901. if (!this.name) {
  64902. return null;
  64903. }
  64904. var serializationObject = _super.prototype.serialize.call(this);
  64905. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64906. return serializationObject;
  64907. };
  64908. MirrorTexture.prototype.dispose = function () {
  64909. _super.prototype.dispose.call(this);
  64910. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64911. };
  64912. return MirrorTexture;
  64913. }(BABYLON.RenderTargetTexture));
  64914. BABYLON.MirrorTexture = MirrorTexture;
  64915. })(BABYLON || (BABYLON = {}));
  64916. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64917. var BABYLON;
  64918. (function (BABYLON) {
  64919. /**
  64920. * Creates a refraction texture used by refraction channel of the standard material.
  64921. * @param name the texture name
  64922. * @param size size of the underlying texture
  64923. * @param scene root scene
  64924. */
  64925. var RefractionTexture = /** @class */ (function (_super) {
  64926. __extends(RefractionTexture, _super);
  64927. function RefractionTexture(name, size, scene, generateMipMaps) {
  64928. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64929. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64930. _this.depth = 2.0;
  64931. _this.onBeforeRenderObservable.add(function () {
  64932. scene.clipPlane = _this.refractionPlane;
  64933. });
  64934. _this.onAfterRenderObservable.add(function () {
  64935. delete scene.clipPlane;
  64936. });
  64937. return _this;
  64938. }
  64939. RefractionTexture.prototype.clone = function () {
  64940. var scene = this.getScene();
  64941. if (!scene) {
  64942. return this;
  64943. }
  64944. var textureSize = this.getSize();
  64945. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64946. // Base texture
  64947. newTexture.hasAlpha = this.hasAlpha;
  64948. newTexture.level = this.level;
  64949. // Refraction Texture
  64950. newTexture.refractionPlane = this.refractionPlane.clone();
  64951. if (this.renderList) {
  64952. newTexture.renderList = this.renderList.slice(0);
  64953. }
  64954. newTexture.depth = this.depth;
  64955. return newTexture;
  64956. };
  64957. RefractionTexture.prototype.serialize = function () {
  64958. if (!this.name) {
  64959. return null;
  64960. }
  64961. var serializationObject = _super.prototype.serialize.call(this);
  64962. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64963. serializationObject.depth = this.depth;
  64964. return serializationObject;
  64965. };
  64966. return RefractionTexture;
  64967. }(BABYLON.RenderTargetTexture));
  64968. BABYLON.RefractionTexture = RefractionTexture;
  64969. })(BABYLON || (BABYLON = {}));
  64970. //# sourceMappingURL=babylon.refractionTexture.js.map
  64971. var BABYLON;
  64972. (function (BABYLON) {
  64973. /**
  64974. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64975. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64976. */
  64977. var DynamicTexture = /** @class */ (function (_super) {
  64978. __extends(DynamicTexture, _super);
  64979. /**
  64980. * Creates a {BABYLON.DynamicTexture}
  64981. * @param name defines the name of the texture
  64982. * @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
  64983. * @param scene defines the scene where you want the texture
  64984. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64985. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64986. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64987. */
  64988. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64989. if (scene === void 0) { scene = null; }
  64990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64991. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64992. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64993. _this.name = name;
  64994. _this._engine = _this.getScene().getEngine();
  64995. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64996. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64997. _this._generateMipMaps = generateMipMaps;
  64998. if (options.getContext) {
  64999. _this._canvas = options;
  65000. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65001. }
  65002. else {
  65003. _this._canvas = document.createElement("canvas");
  65004. if (options.width || options.width === 0) {
  65005. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65006. }
  65007. else {
  65008. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  65009. }
  65010. }
  65011. var textureSize = _this.getSize();
  65012. _this._canvas.width = textureSize.width;
  65013. _this._canvas.height = textureSize.height;
  65014. _this._context = _this._canvas.getContext("2d");
  65015. return _this;
  65016. }
  65017. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  65018. /**
  65019. * Gets the current state of canRescale
  65020. */
  65021. get: function () {
  65022. return true;
  65023. },
  65024. enumerable: true,
  65025. configurable: true
  65026. });
  65027. DynamicTexture.prototype._recreate = function (textureSize) {
  65028. this._canvas.width = textureSize.width;
  65029. this._canvas.height = textureSize.height;
  65030. this.releaseInternalTexture();
  65031. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65032. };
  65033. /**
  65034. * Scales the texture
  65035. * @param ratio the scale factor to apply to both width and height
  65036. */
  65037. DynamicTexture.prototype.scale = function (ratio) {
  65038. var textureSize = this.getSize();
  65039. textureSize.width *= ratio;
  65040. textureSize.height *= ratio;
  65041. this._recreate(textureSize);
  65042. };
  65043. /**
  65044. * Resizes the texture
  65045. * @param width the new width
  65046. * @param height the new height
  65047. */
  65048. DynamicTexture.prototype.scaleTo = function (width, height) {
  65049. var textureSize = this.getSize();
  65050. textureSize.width = width;
  65051. textureSize.height = height;
  65052. this._recreate(textureSize);
  65053. };
  65054. /**
  65055. * Gets the context of the canvas used by the texture
  65056. * @returns the canvas context of the dynamic texture
  65057. */
  65058. DynamicTexture.prototype.getContext = function () {
  65059. return this._context;
  65060. };
  65061. /**
  65062. * Clears the texture
  65063. */
  65064. DynamicTexture.prototype.clear = function () {
  65065. var size = this.getSize();
  65066. this._context.fillRect(0, 0, size.width, size.height);
  65067. };
  65068. /**
  65069. * Updates the texture
  65070. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65071. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65072. */
  65073. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65074. if (premulAlpha === void 0) { premulAlpha = false; }
  65075. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65076. };
  65077. /**
  65078. * Draws text onto the texture
  65079. * @param text defines the text to be drawn
  65080. * @param x defines the placement of the text from the left
  65081. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65082. * @param font defines the font to be used with font-style, font-size, font-name
  65083. * @param color defines the color used for the text
  65084. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65085. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65086. * @param update defines whether texture is immediately update (default is true)
  65087. */
  65088. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65089. if (update === void 0) { update = true; }
  65090. var size = this.getSize();
  65091. if (clearColor) {
  65092. this._context.fillStyle = clearColor;
  65093. this._context.fillRect(0, 0, size.width, size.height);
  65094. }
  65095. this._context.font = font;
  65096. if (x === null || x === undefined) {
  65097. var textSize = this._context.measureText(text);
  65098. x = (size.width - textSize.width) / 2;
  65099. }
  65100. if (y === null || y === undefined) {
  65101. var fontSize = parseInt((font.replace(/\D/g, '')));
  65102. y = (size.height / 2) + (fontSize / 3.65);
  65103. }
  65104. this._context.fillStyle = color;
  65105. this._context.fillText(text, x, y);
  65106. if (update) {
  65107. this.update(invertY);
  65108. }
  65109. };
  65110. /**
  65111. * Clones the texture
  65112. * @returns the clone of the texture.
  65113. */
  65114. DynamicTexture.prototype.clone = function () {
  65115. var scene = this.getScene();
  65116. if (!scene) {
  65117. return this;
  65118. }
  65119. var textureSize = this.getSize();
  65120. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65121. // Base texture
  65122. newTexture.hasAlpha = this.hasAlpha;
  65123. newTexture.level = this.level;
  65124. // Dynamic Texture
  65125. newTexture.wrapU = this.wrapU;
  65126. newTexture.wrapV = this.wrapV;
  65127. return newTexture;
  65128. };
  65129. /** @hidden */
  65130. DynamicTexture.prototype._rebuild = function () {
  65131. this.update();
  65132. };
  65133. return DynamicTexture;
  65134. }(BABYLON.Texture));
  65135. BABYLON.DynamicTexture = DynamicTexture;
  65136. })(BABYLON || (BABYLON = {}));
  65137. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65138. var BABYLON;
  65139. (function (BABYLON) {
  65140. var VideoTexture = /** @class */ (function (_super) {
  65141. __extends(VideoTexture, _super);
  65142. /**
  65143. * Creates a video texture.
  65144. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65145. * @param {string | null} name optional name, will detect from video source, if not defined
  65146. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65147. * @param {BABYLON.Scene} scene is obviously the current scene.
  65148. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65149. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65150. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65151. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65152. */
  65153. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65154. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65155. if (invertY === void 0) { invertY = false; }
  65156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65157. if (settings === void 0) { settings = {
  65158. autoPlay: true,
  65159. loop: true,
  65160. autoUpdateTexture: true,
  65161. }; }
  65162. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65163. _this._stillImageCaptured = false;
  65164. _this._createInternalTexture = function () {
  65165. if (_this._texture != null) {
  65166. return;
  65167. }
  65168. if (!_this._engine.needPOTTextures ||
  65169. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65170. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65171. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65172. }
  65173. else {
  65174. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65175. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65176. _this._generateMipMaps = false;
  65177. }
  65178. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65179. if (!_this.video.autoplay) {
  65180. var oldHandler_1 = _this.video.onplaying;
  65181. _this.video.onplaying = function () {
  65182. _this.video.onplaying = oldHandler_1;
  65183. _this._texture.isReady = true;
  65184. _this._updateInternalTexture();
  65185. _this.video.pause();
  65186. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65187. _this.onLoadObservable.notifyObservers(_this);
  65188. }
  65189. };
  65190. _this.video.play();
  65191. }
  65192. else {
  65193. _this._texture.isReady = true;
  65194. _this._updateInternalTexture();
  65195. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65196. _this.onLoadObservable.notifyObservers(_this);
  65197. }
  65198. }
  65199. };
  65200. _this.reset = function () {
  65201. if (_this._texture == null) {
  65202. return;
  65203. }
  65204. _this._texture.dispose();
  65205. _this._texture = null;
  65206. };
  65207. _this._updateInternalTexture = function (e) {
  65208. if (_this._texture == null || !_this._texture.isReady) {
  65209. return;
  65210. }
  65211. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65212. return;
  65213. }
  65214. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65215. };
  65216. _this._engine = _this.getScene().getEngine();
  65217. _this._generateMipMaps = generateMipMaps;
  65218. _this._samplingMode = samplingMode;
  65219. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65220. _this.name = name || _this._getName(src);
  65221. _this.video = _this._getVideo(src);
  65222. if (settings.autoPlay !== undefined) {
  65223. _this.video.autoplay = settings.autoPlay;
  65224. }
  65225. if (settings.loop !== undefined) {
  65226. _this.video.loop = settings.loop;
  65227. }
  65228. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65229. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65230. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65231. _this.video.addEventListener("emptied", _this.reset);
  65232. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65233. _this._createInternalTexture();
  65234. }
  65235. return _this;
  65236. }
  65237. VideoTexture.prototype._getName = function (src) {
  65238. if (src instanceof HTMLVideoElement) {
  65239. return src.currentSrc;
  65240. }
  65241. if (typeof src === "object") {
  65242. return src.toString();
  65243. }
  65244. return src;
  65245. };
  65246. ;
  65247. VideoTexture.prototype._getVideo = function (src) {
  65248. if (src instanceof HTMLVideoElement) {
  65249. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65250. return src;
  65251. }
  65252. var video = document.createElement("video");
  65253. if (typeof src === "string") {
  65254. BABYLON.Tools.SetCorsBehavior(src, video);
  65255. video.src = src;
  65256. }
  65257. else {
  65258. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65259. src.forEach(function (url) {
  65260. var source = document.createElement("source");
  65261. source.src = url;
  65262. video.appendChild(source);
  65263. });
  65264. }
  65265. return video;
  65266. };
  65267. ;
  65268. /**
  65269. * Internal method to initiate `update`.
  65270. */
  65271. VideoTexture.prototype._rebuild = function () {
  65272. this.update();
  65273. };
  65274. /**
  65275. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65276. */
  65277. VideoTexture.prototype.update = function () {
  65278. if (!this.autoUpdateTexture) {
  65279. // Expecting user to call `updateTexture` manually
  65280. return;
  65281. }
  65282. this.updateTexture(true);
  65283. };
  65284. /**
  65285. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65286. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65287. */
  65288. VideoTexture.prototype.updateTexture = function (isVisible) {
  65289. if (!isVisible) {
  65290. return;
  65291. }
  65292. if (this.video.paused && this._stillImageCaptured) {
  65293. return;
  65294. }
  65295. this._stillImageCaptured = true;
  65296. this._updateInternalTexture();
  65297. };
  65298. /**
  65299. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65300. * @param url New url.
  65301. */
  65302. VideoTexture.prototype.updateURL = function (url) {
  65303. this.video.src = url;
  65304. };
  65305. VideoTexture.prototype.dispose = function () {
  65306. _super.prototype.dispose.call(this);
  65307. this.video.removeEventListener("canplay", this._createInternalTexture);
  65308. this.video.removeEventListener("paused", this._updateInternalTexture);
  65309. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65310. this.video.removeEventListener("emptied", this.reset);
  65311. this.video.pause();
  65312. };
  65313. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65314. var video = document.createElement("video");
  65315. var constraintsDeviceId;
  65316. if (constraints && constraints.deviceId) {
  65317. constraintsDeviceId = {
  65318. exact: constraints.deviceId,
  65319. };
  65320. }
  65321. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65322. if (navigator.mediaDevices) {
  65323. navigator.mediaDevices.getUserMedia({ video: constraints })
  65324. .then(function (stream) {
  65325. if (video.mozSrcObject !== undefined) {
  65326. // hack for Firefox < 19
  65327. video.mozSrcObject = stream;
  65328. }
  65329. else {
  65330. video.srcObject = stream;
  65331. }
  65332. var onPlaying = function () {
  65333. if (onReady) {
  65334. onReady(new VideoTexture("video", video, scene, true, true));
  65335. }
  65336. video.removeEventListener("playing", onPlaying);
  65337. };
  65338. video.addEventListener("playing", onPlaying);
  65339. video.play();
  65340. })
  65341. .catch(function (err) {
  65342. BABYLON.Tools.Error(err.name);
  65343. });
  65344. }
  65345. else {
  65346. navigator.getUserMedia =
  65347. navigator.getUserMedia ||
  65348. navigator.webkitGetUserMedia ||
  65349. navigator.mozGetUserMedia ||
  65350. navigator.msGetUserMedia;
  65351. if (navigator.getUserMedia) {
  65352. navigator.getUserMedia({
  65353. video: {
  65354. deviceId: constraintsDeviceId,
  65355. width: {
  65356. min: (constraints && constraints.minWidth) || 256,
  65357. max: (constraints && constraints.maxWidth) || 640,
  65358. },
  65359. height: {
  65360. min: (constraints && constraints.minHeight) || 256,
  65361. max: (constraints && constraints.maxHeight) || 480,
  65362. },
  65363. },
  65364. }, function (stream) {
  65365. if (video.mozSrcObject !== undefined) {
  65366. // hack for Firefox < 19
  65367. video.mozSrcObject = stream;
  65368. }
  65369. else {
  65370. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65371. }
  65372. video.play();
  65373. if (onReady) {
  65374. onReady(new VideoTexture("video", video, scene, true, true));
  65375. }
  65376. }, function (e) {
  65377. BABYLON.Tools.Error(e.name);
  65378. });
  65379. }
  65380. }
  65381. };
  65382. return VideoTexture;
  65383. }(BABYLON.Texture));
  65384. BABYLON.VideoTexture = VideoTexture;
  65385. })(BABYLON || (BABYLON = {}));
  65386. //# sourceMappingURL=babylon.videoTexture.js.map
  65387. var BABYLON;
  65388. (function (BABYLON) {
  65389. var RawTexture = /** @class */ (function (_super) {
  65390. __extends(RawTexture, _super);
  65391. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65393. if (invertY === void 0) { invertY = false; }
  65394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65395. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65396. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65397. _this.format = format;
  65398. _this._engine = scene.getEngine();
  65399. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65400. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65401. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65402. return _this;
  65403. }
  65404. RawTexture.prototype.update = function (data) {
  65405. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65406. };
  65407. // Statics
  65408. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65409. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65410. if (invertY === void 0) { invertY = false; }
  65411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65412. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65413. };
  65414. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65415. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65416. if (invertY === void 0) { invertY = false; }
  65417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65418. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65419. };
  65420. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65421. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65422. if (invertY === void 0) { invertY = false; }
  65423. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65424. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65425. };
  65426. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65427. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65428. if (invertY === void 0) { invertY = false; }
  65429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65430. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65431. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65432. };
  65433. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65434. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65435. if (invertY === void 0) { invertY = false; }
  65436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65437. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65438. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65439. };
  65440. return RawTexture;
  65441. }(BABYLON.Texture));
  65442. BABYLON.RawTexture = RawTexture;
  65443. })(BABYLON || (BABYLON = {}));
  65444. //# sourceMappingURL=babylon.rawTexture.js.map
  65445. var BABYLON;
  65446. (function (BABYLON) {
  65447. /**
  65448. * Class used to store 3D textures containing user data
  65449. */
  65450. var RawTexture3D = /** @class */ (function (_super) {
  65451. __extends(RawTexture3D, _super);
  65452. /**
  65453. * Create a new RawTexture3D
  65454. * @param data defines the data of the texture
  65455. * @param width defines the width of the texture
  65456. * @param height defines the height of the texture
  65457. * @param depth defines the depth of the texture
  65458. * @param format defines the texture format to use
  65459. * @param scene defines the hosting scene
  65460. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65461. * @param invertY defines if texture must be stored with Y axis inverted
  65462. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65463. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65464. */
  65465. function RawTexture3D(data, width, height, depth,
  65466. /** Gets or sets the texture format to use */
  65467. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65469. if (invertY === void 0) { invertY = false; }
  65470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65471. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65472. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65473. _this.format = format;
  65474. _this._engine = scene.getEngine();
  65475. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65476. _this.is3D = true;
  65477. return _this;
  65478. }
  65479. /**
  65480. * Update the texture with new data
  65481. * @param data defines the data to store in the texture
  65482. */
  65483. RawTexture3D.prototype.update = function (data) {
  65484. if (!this._texture) {
  65485. return;
  65486. }
  65487. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65488. };
  65489. return RawTexture3D;
  65490. }(BABYLON.Texture));
  65491. BABYLON.RawTexture3D = RawTexture3D;
  65492. })(BABYLON || (BABYLON = {}));
  65493. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65494. var BABYLON;
  65495. (function (BABYLON) {
  65496. /**
  65497. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65498. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65499. */
  65500. var PostProcess = /** @class */ (function () {
  65501. /**
  65502. * Creates a new instance PostProcess
  65503. * @param name The name of the PostProcess.
  65504. * @param fragmentUrl The url of the fragment shader to be used.
  65505. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65506. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65507. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65508. * @param camera The camera to apply the render pass to.
  65509. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65510. * @param engine The engine which the post process will be applied. (default: current engine)
  65511. * @param reusable If the post process can be reused on the same frame. (default: false)
  65512. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65513. * @param textureType Type of textures used when performing the post process. (default: 0)
  65514. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65515. * @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
  65516. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65517. */
  65518. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65520. if (defines === void 0) { defines = null; }
  65521. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65522. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65523. if (blockCompilation === void 0) { blockCompilation = false; }
  65524. this.name = name;
  65525. /**
  65526. * Width of the texture to apply the post process on
  65527. */
  65528. this.width = -1;
  65529. /**
  65530. * Height of the texture to apply the post process on
  65531. */
  65532. this.height = -1;
  65533. /**
  65534. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65535. */
  65536. this._outputTexture = null;
  65537. /**
  65538. * If the buffer needs to be cleared before applying the post process. (default: true)
  65539. * Should be set to false if shader will overwrite all previous pixels.
  65540. */
  65541. this.autoClear = true;
  65542. /**
  65543. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65544. */
  65545. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65546. /**
  65547. * Animations to be used for the post processing
  65548. */
  65549. this.animations = new Array();
  65550. /**
  65551. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65552. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65553. */
  65554. this.enablePixelPerfectMode = false;
  65555. /**
  65556. * Force the postprocess to be applied without taking in account viewport
  65557. */
  65558. this.forceFullscreenViewport = true;
  65559. /**
  65560. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65561. *
  65562. * | Value | Type | Description |
  65563. * | ----- | ----------------------------------- | ----------- |
  65564. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65565. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65566. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65567. *
  65568. */
  65569. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65570. /**
  65571. * Force textures to be a power of two (default: false)
  65572. */
  65573. this.alwaysForcePOT = false;
  65574. /**
  65575. * Number of sample textures (default: 1)
  65576. */
  65577. this.samples = 1;
  65578. /**
  65579. * Modify the scale of the post process to be the same as the viewport (default: false)
  65580. */
  65581. this.adaptScaleToCurrentViewport = false;
  65582. this._reusable = false;
  65583. /**
  65584. * Smart array of input and output textures for the post process.
  65585. */
  65586. this._textures = new BABYLON.SmartArray(2);
  65587. /**
  65588. * The index in _textures that corresponds to the output texture.
  65589. */
  65590. this._currentRenderTextureInd = 0;
  65591. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65592. this._texelSize = BABYLON.Vector2.Zero();
  65593. // Events
  65594. /**
  65595. * An event triggered when the postprocess is activated.
  65596. */
  65597. this.onActivateObservable = new BABYLON.Observable();
  65598. /**
  65599. * An event triggered when the postprocess changes its size.
  65600. */
  65601. this.onSizeChangedObservable = new BABYLON.Observable();
  65602. /**
  65603. * An event triggered when the postprocess applies its effect.
  65604. */
  65605. this.onApplyObservable = new BABYLON.Observable();
  65606. /**
  65607. * An event triggered before rendering the postprocess
  65608. */
  65609. this.onBeforeRenderObservable = new BABYLON.Observable();
  65610. /**
  65611. * An event triggered after rendering the postprocess
  65612. */
  65613. this.onAfterRenderObservable = new BABYLON.Observable();
  65614. if (camera != null) {
  65615. this._camera = camera;
  65616. this._scene = camera.getScene();
  65617. camera.attachPostProcess(this);
  65618. this._engine = this._scene.getEngine();
  65619. this._scene.postProcesses.push(this);
  65620. }
  65621. else if (engine) {
  65622. this._engine = engine;
  65623. this._engine.postProcesses.push(this);
  65624. }
  65625. this._options = options;
  65626. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65627. this._reusable = reusable || false;
  65628. this._textureType = textureType;
  65629. this._samplers = samplers || [];
  65630. this._samplers.push("textureSampler");
  65631. this._fragmentUrl = fragmentUrl;
  65632. this._vertexUrl = vertexUrl;
  65633. this._parameters = parameters || [];
  65634. this._parameters.push("scale");
  65635. this._indexParameters = indexParameters;
  65636. if (!blockCompilation) {
  65637. this.updateEffect(defines);
  65638. }
  65639. }
  65640. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65641. /**
  65642. * A function that is added to the onActivateObservable
  65643. */
  65644. set: function (callback) {
  65645. if (this._onActivateObserver) {
  65646. this.onActivateObservable.remove(this._onActivateObserver);
  65647. }
  65648. if (callback) {
  65649. this._onActivateObserver = this.onActivateObservable.add(callback);
  65650. }
  65651. },
  65652. enumerable: true,
  65653. configurable: true
  65654. });
  65655. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65656. /**
  65657. * A function that is added to the onSizeChangedObservable
  65658. */
  65659. set: function (callback) {
  65660. if (this._onSizeChangedObserver) {
  65661. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65662. }
  65663. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65664. },
  65665. enumerable: true,
  65666. configurable: true
  65667. });
  65668. Object.defineProperty(PostProcess.prototype, "onApply", {
  65669. /**
  65670. * A function that is added to the onApplyObservable
  65671. */
  65672. set: function (callback) {
  65673. if (this._onApplyObserver) {
  65674. this.onApplyObservable.remove(this._onApplyObserver);
  65675. }
  65676. this._onApplyObserver = this.onApplyObservable.add(callback);
  65677. },
  65678. enumerable: true,
  65679. configurable: true
  65680. });
  65681. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65682. /**
  65683. * A function that is added to the onBeforeRenderObservable
  65684. */
  65685. set: function (callback) {
  65686. if (this._onBeforeRenderObserver) {
  65687. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65688. }
  65689. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65690. },
  65691. enumerable: true,
  65692. configurable: true
  65693. });
  65694. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65695. /**
  65696. * A function that is added to the onAfterRenderObservable
  65697. */
  65698. set: function (callback) {
  65699. if (this._onAfterRenderObserver) {
  65700. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65701. }
  65702. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65708. /**
  65709. * 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
  65710. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65711. */
  65712. get: function () {
  65713. return this._textures.data[this._currentRenderTextureInd];
  65714. },
  65715. set: function (value) {
  65716. this._forcedOutputTexture = value;
  65717. },
  65718. enumerable: true,
  65719. configurable: true
  65720. });
  65721. /**
  65722. * Gets the camera which post process is applied to.
  65723. * @returns The camera the post process is applied to.
  65724. */
  65725. PostProcess.prototype.getCamera = function () {
  65726. return this._camera;
  65727. };
  65728. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65729. /**
  65730. * Gets the texel size of the postprocess.
  65731. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65732. */
  65733. get: function () {
  65734. if (this._shareOutputWithPostProcess) {
  65735. return this._shareOutputWithPostProcess.texelSize;
  65736. }
  65737. if (this._forcedOutputTexture) {
  65738. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65739. }
  65740. return this._texelSize;
  65741. },
  65742. enumerable: true,
  65743. configurable: true
  65744. });
  65745. /**
  65746. * Gets the engine which this post process belongs to.
  65747. * @returns The engine the post process was enabled with.
  65748. */
  65749. PostProcess.prototype.getEngine = function () {
  65750. return this._engine;
  65751. };
  65752. /**
  65753. * The effect that is created when initializing the post process.
  65754. * @returns The created effect corrisponding the the postprocess.
  65755. */
  65756. PostProcess.prototype.getEffect = function () {
  65757. return this._effect;
  65758. };
  65759. /**
  65760. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65761. * @param postProcess The post process to share the output with.
  65762. * @returns This post process.
  65763. */
  65764. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65765. this._disposeTextures();
  65766. this._shareOutputWithPostProcess = postProcess;
  65767. return this;
  65768. };
  65769. /**
  65770. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65771. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65772. */
  65773. PostProcess.prototype.useOwnOutput = function () {
  65774. if (this._textures.length == 0) {
  65775. this._textures = new BABYLON.SmartArray(2);
  65776. }
  65777. this._shareOutputWithPostProcess = null;
  65778. };
  65779. /**
  65780. * Updates the effect with the current post process compile time values and recompiles the shader.
  65781. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65782. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65783. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65784. * @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
  65785. * @param onCompiled Called when the shader has been compiled.
  65786. * @param onError Called if there is an error when compiling a shader.
  65787. */
  65788. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65789. if (defines === void 0) { defines = null; }
  65790. if (uniforms === void 0) { uniforms = null; }
  65791. if (samplers === void 0) { samplers = null; }
  65792. 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);
  65793. };
  65794. /**
  65795. * The post process is reusable if it can be used multiple times within one frame.
  65796. * @returns If the post process is reusable
  65797. */
  65798. PostProcess.prototype.isReusable = function () {
  65799. return this._reusable;
  65800. };
  65801. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65802. PostProcess.prototype.markTextureDirty = function () {
  65803. this.width = -1;
  65804. };
  65805. /**
  65806. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65807. * 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.
  65808. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65809. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65810. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65811. * @returns The target texture that was bound to be written to.
  65812. */
  65813. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65814. var _this = this;
  65815. if (sourceTexture === void 0) { sourceTexture = null; }
  65816. camera = camera || this._camera;
  65817. var scene = camera.getScene();
  65818. var engine = scene.getEngine();
  65819. var maxSize = engine.getCaps().maxTextureSize;
  65820. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65821. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65822. // 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
  65823. var webVRCamera = camera.parent;
  65824. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65825. requiredWidth /= 2;
  65826. }
  65827. var desiredWidth = (this._options.width || requiredWidth);
  65828. var desiredHeight = this._options.height || requiredHeight;
  65829. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65830. if (this.adaptScaleToCurrentViewport) {
  65831. var currentViewport = engine.currentViewport;
  65832. if (currentViewport) {
  65833. desiredWidth *= currentViewport.width;
  65834. desiredHeight *= currentViewport.height;
  65835. }
  65836. }
  65837. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65838. if (!this._options.width) {
  65839. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65840. }
  65841. if (!this._options.height) {
  65842. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65843. }
  65844. }
  65845. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65846. if (this._textures.length > 0) {
  65847. for (var i = 0; i < this._textures.length; i++) {
  65848. this._engine._releaseTexture(this._textures.data[i]);
  65849. }
  65850. this._textures.reset();
  65851. }
  65852. this.width = desiredWidth;
  65853. this.height = desiredHeight;
  65854. var textureSize = { width: this.width, height: this.height };
  65855. var textureOptions = {
  65856. generateMipMaps: false,
  65857. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65858. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65859. samplingMode: this.renderTargetSamplingMode,
  65860. type: this._textureType
  65861. };
  65862. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65863. if (this._reusable) {
  65864. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65865. }
  65866. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65867. this.onSizeChangedObservable.notifyObservers(this);
  65868. }
  65869. this._textures.forEach(function (texture) {
  65870. if (texture.samples !== _this.samples) {
  65871. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65872. }
  65873. });
  65874. }
  65875. var target;
  65876. if (this._shareOutputWithPostProcess) {
  65877. target = this._shareOutputWithPostProcess.inputTexture;
  65878. }
  65879. else if (this._forcedOutputTexture) {
  65880. target = this._forcedOutputTexture;
  65881. this.width = this._forcedOutputTexture.width;
  65882. this.height = this._forcedOutputTexture.height;
  65883. }
  65884. else {
  65885. target = this.inputTexture;
  65886. }
  65887. // Bind the input of this post process to be used as the output of the previous post process.
  65888. if (this.enablePixelPerfectMode) {
  65889. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65890. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65891. }
  65892. else {
  65893. this._scaleRatio.copyFromFloats(1, 1);
  65894. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65895. }
  65896. this.onActivateObservable.notifyObservers(camera);
  65897. // Clear
  65898. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65899. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65900. }
  65901. if (this._reusable) {
  65902. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65903. }
  65904. return target;
  65905. };
  65906. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65907. /**
  65908. * If the post process is supported.
  65909. */
  65910. get: function () {
  65911. return this._effect.isSupported;
  65912. },
  65913. enumerable: true,
  65914. configurable: true
  65915. });
  65916. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65917. /**
  65918. * The aspect ratio of the output texture.
  65919. */
  65920. get: function () {
  65921. if (this._shareOutputWithPostProcess) {
  65922. return this._shareOutputWithPostProcess.aspectRatio;
  65923. }
  65924. if (this._forcedOutputTexture) {
  65925. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65926. }
  65927. return this.width / this.height;
  65928. },
  65929. enumerable: true,
  65930. configurable: true
  65931. });
  65932. /**
  65933. * Get a value indicating if the post-process is ready to be used
  65934. * @returns true if the post-process is ready (shader is compiled)
  65935. */
  65936. PostProcess.prototype.isReady = function () {
  65937. return this._effect && this._effect.isReady();
  65938. };
  65939. /**
  65940. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65941. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65942. */
  65943. PostProcess.prototype.apply = function () {
  65944. // Check
  65945. if (!this._effect || !this._effect.isReady())
  65946. return null;
  65947. // States
  65948. this._engine.enableEffect(this._effect);
  65949. this._engine.setState(false);
  65950. this._engine.setDepthBuffer(false);
  65951. this._engine.setDepthWrite(false);
  65952. // Alpha
  65953. this._engine.setAlphaMode(this.alphaMode);
  65954. if (this.alphaConstants) {
  65955. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65956. }
  65957. // Bind the output texture of the preivous post process as the input to this post process.
  65958. var source;
  65959. if (this._shareOutputWithPostProcess) {
  65960. source = this._shareOutputWithPostProcess.inputTexture;
  65961. }
  65962. else if (this._forcedOutputTexture) {
  65963. source = this._forcedOutputTexture;
  65964. }
  65965. else {
  65966. source = this.inputTexture;
  65967. }
  65968. this._effect._bindTexture("textureSampler", source);
  65969. // Parameters
  65970. this._effect.setVector2("scale", this._scaleRatio);
  65971. this.onApplyObservable.notifyObservers(this._effect);
  65972. return this._effect;
  65973. };
  65974. PostProcess.prototype._disposeTextures = function () {
  65975. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65976. return;
  65977. }
  65978. if (this._textures.length > 0) {
  65979. for (var i = 0; i < this._textures.length; i++) {
  65980. this._engine._releaseTexture(this._textures.data[i]);
  65981. }
  65982. }
  65983. this._textures.dispose();
  65984. };
  65985. /**
  65986. * Disposes the post process.
  65987. * @param camera The camera to dispose the post process on.
  65988. */
  65989. PostProcess.prototype.dispose = function (camera) {
  65990. camera = camera || this._camera;
  65991. this._disposeTextures();
  65992. if (this._scene) {
  65993. var index_1 = this._scene.postProcesses.indexOf(this);
  65994. if (index_1 !== -1) {
  65995. this._scene.postProcesses.splice(index_1, 1);
  65996. }
  65997. }
  65998. else {
  65999. var index_2 = this._engine.postProcesses.indexOf(this);
  66000. if (index_2 !== -1) {
  66001. this._engine.postProcesses.splice(index_2, 1);
  66002. }
  66003. }
  66004. if (!camera) {
  66005. return;
  66006. }
  66007. camera.detachPostProcess(this);
  66008. var index = camera._postProcesses.indexOf(this);
  66009. if (index === 0 && camera._postProcesses.length > 0) {
  66010. var firstPostProcess = this._camera._getFirstPostProcess();
  66011. if (firstPostProcess) {
  66012. firstPostProcess.markTextureDirty();
  66013. }
  66014. }
  66015. this.onActivateObservable.clear();
  66016. this.onAfterRenderObservable.clear();
  66017. this.onApplyObservable.clear();
  66018. this.onBeforeRenderObservable.clear();
  66019. this.onSizeChangedObservable.clear();
  66020. };
  66021. return PostProcess;
  66022. }());
  66023. BABYLON.PostProcess = PostProcess;
  66024. })(BABYLON || (BABYLON = {}));
  66025. //# sourceMappingURL=babylon.postProcess.js.map
  66026. var BABYLON;
  66027. (function (BABYLON) {
  66028. var PassPostProcess = /** @class */ (function (_super) {
  66029. __extends(PassPostProcess, _super);
  66030. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66031. if (camera === void 0) { camera = null; }
  66032. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66033. if (blockCompilation === void 0) { blockCompilation = false; }
  66034. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66035. }
  66036. return PassPostProcess;
  66037. }(BABYLON.PostProcess));
  66038. BABYLON.PassPostProcess = PassPostProcess;
  66039. })(BABYLON || (BABYLON = {}));
  66040. //# sourceMappingURL=babylon.passPostProcess.js.map
  66041. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66042. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66043. s = arguments[i];
  66044. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66045. t[p] = s[p];
  66046. }
  66047. return t;
  66048. };
  66049. var BABYLON;
  66050. (function (BABYLON) {
  66051. /**
  66052. * Default implementation IShadowGenerator.
  66053. * This is the main object responsible of generating shadows in the framework.
  66054. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66055. */
  66056. var ShadowGenerator = /** @class */ (function () {
  66057. /**
  66058. * Creates a ShadowGenerator object.
  66059. * A ShadowGenerator is the required tool to use the shadows.
  66060. * Each light casting shadows needs to use its own ShadowGenerator.
  66061. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66062. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66063. * @param light The light object generating the shadows.
  66064. * @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.
  66065. */
  66066. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66067. this._bias = 0.00005;
  66068. this._normalBias = 0;
  66069. this._blurBoxOffset = 1;
  66070. this._blurScale = 2;
  66071. this._blurKernel = 1;
  66072. this._useKernelBlur = false;
  66073. this._filter = ShadowGenerator.FILTER_NONE;
  66074. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66075. this._contactHardeningLightSizeUVRatio = 0.1;
  66076. this._darkness = 0;
  66077. this._transparencyShadow = false;
  66078. /**
  66079. * Controls the extent to which the shadows fade out at the edge of the frustum
  66080. * Used only by directionals and spots
  66081. */
  66082. this.frustumEdgeFalloff = 0;
  66083. /**
  66084. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66085. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66086. * It might on the other hand introduce peter panning.
  66087. */
  66088. this.forceBackFacesOnly = false;
  66089. this._lightDirection = BABYLON.Vector3.Zero();
  66090. this._viewMatrix = BABYLON.Matrix.Zero();
  66091. this._projectionMatrix = BABYLON.Matrix.Zero();
  66092. this._transformMatrix = BABYLON.Matrix.Zero();
  66093. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66094. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66095. this._currentFaceIndex = 0;
  66096. this._currentFaceIndexCache = 0;
  66097. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66098. this._mapSize = mapSize;
  66099. this._light = light;
  66100. this._scene = light.getScene();
  66101. light._shadowGenerator = this;
  66102. // Texture type fallback from float to int if not supported.
  66103. var caps = this._scene.getEngine().getCaps();
  66104. if (!useFullFloatFirst) {
  66105. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66106. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66107. }
  66108. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66109. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66110. }
  66111. else {
  66112. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66113. }
  66114. }
  66115. else {
  66116. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66117. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66118. }
  66119. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66120. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66121. }
  66122. else {
  66123. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66124. }
  66125. }
  66126. this._initializeGenerator();
  66127. this._applyFilterValues();
  66128. }
  66129. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66130. /**
  66131. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66132. */
  66133. get: function () {
  66134. return this._bias;
  66135. },
  66136. /**
  66137. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66138. */
  66139. set: function (bias) {
  66140. this._bias = bias;
  66141. },
  66142. enumerable: true,
  66143. configurable: true
  66144. });
  66145. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66146. /**
  66147. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66148. */
  66149. get: function () {
  66150. return this._normalBias;
  66151. },
  66152. /**
  66153. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66154. */
  66155. set: function (normalBias) {
  66156. this._normalBias = normalBias;
  66157. },
  66158. enumerable: true,
  66159. configurable: true
  66160. });
  66161. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66162. /**
  66163. * Gets the blur box offset: offset applied during the blur pass.
  66164. * Only usefull if useKernelBlur = false
  66165. */
  66166. get: function () {
  66167. return this._blurBoxOffset;
  66168. },
  66169. /**
  66170. * Sets the blur box offset: offset applied during the blur pass.
  66171. * Only usefull if useKernelBlur = false
  66172. */
  66173. set: function (value) {
  66174. if (this._blurBoxOffset === value) {
  66175. return;
  66176. }
  66177. this._blurBoxOffset = value;
  66178. this._disposeBlurPostProcesses();
  66179. },
  66180. enumerable: true,
  66181. configurable: true
  66182. });
  66183. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66184. /**
  66185. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66186. * 2 means half of the size.
  66187. */
  66188. get: function () {
  66189. return this._blurScale;
  66190. },
  66191. /**
  66192. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66193. * 2 means half of the size.
  66194. */
  66195. set: function (value) {
  66196. if (this._blurScale === value) {
  66197. return;
  66198. }
  66199. this._blurScale = value;
  66200. this._disposeBlurPostProcesses();
  66201. },
  66202. enumerable: true,
  66203. configurable: true
  66204. });
  66205. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66206. /**
  66207. * Gets the blur kernel: kernel size of the blur pass.
  66208. * Only usefull if useKernelBlur = true
  66209. */
  66210. get: function () {
  66211. return this._blurKernel;
  66212. },
  66213. /**
  66214. * Sets the blur kernel: kernel size of the blur pass.
  66215. * Only usefull if useKernelBlur = true
  66216. */
  66217. set: function (value) {
  66218. if (this._blurKernel === value) {
  66219. return;
  66220. }
  66221. this._blurKernel = value;
  66222. this._disposeBlurPostProcesses();
  66223. },
  66224. enumerable: true,
  66225. configurable: true
  66226. });
  66227. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66228. /**
  66229. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66230. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66231. */
  66232. get: function () {
  66233. return this._useKernelBlur;
  66234. },
  66235. /**
  66236. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66237. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66238. */
  66239. set: function (value) {
  66240. if (this._useKernelBlur === value) {
  66241. return;
  66242. }
  66243. this._useKernelBlur = value;
  66244. this._disposeBlurPostProcesses();
  66245. },
  66246. enumerable: true,
  66247. configurable: true
  66248. });
  66249. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66250. /**
  66251. * Gets the depth scale used in ESM mode.
  66252. */
  66253. get: function () {
  66254. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66255. },
  66256. /**
  66257. * Sets the depth scale used in ESM mode.
  66258. * This can override the scale stored on the light.
  66259. */
  66260. set: function (value) {
  66261. this._depthScale = value;
  66262. },
  66263. enumerable: true,
  66264. configurable: true
  66265. });
  66266. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66267. /**
  66268. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66269. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66270. */
  66271. get: function () {
  66272. return this._filter;
  66273. },
  66274. /**
  66275. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66276. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66277. */
  66278. set: function (value) {
  66279. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66280. if (this._light.needCube()) {
  66281. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66282. this.useExponentialShadowMap = true;
  66283. return;
  66284. }
  66285. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66286. this.useCloseExponentialShadowMap = true;
  66287. return;
  66288. }
  66289. // PCF on cubemap would also be expensive
  66290. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66291. this.usePoissonSampling = true;
  66292. return;
  66293. }
  66294. }
  66295. // Weblg1 fallback for PCF.
  66296. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66297. if (this._scene.getEngine().webGLVersion === 1) {
  66298. this.usePoissonSampling = true;
  66299. return;
  66300. }
  66301. }
  66302. if (this._filter === value) {
  66303. return;
  66304. }
  66305. this._filter = value;
  66306. this._disposeBlurPostProcesses();
  66307. this._applyFilterValues();
  66308. this._light._markMeshesAsLightDirty();
  66309. },
  66310. enumerable: true,
  66311. configurable: true
  66312. });
  66313. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66314. /**
  66315. * Gets if the current filter is set to Poisson Sampling.
  66316. */
  66317. get: function () {
  66318. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66319. },
  66320. /**
  66321. * Sets the current filter to Poisson Sampling.
  66322. */
  66323. set: function (value) {
  66324. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66325. return;
  66326. }
  66327. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66328. },
  66329. enumerable: true,
  66330. configurable: true
  66331. });
  66332. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66333. /**
  66334. * Gets if the current filter is set to VSM.
  66335. * DEPRECATED. Should use useExponentialShadowMap instead.
  66336. */
  66337. get: function () {
  66338. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66339. return this.useExponentialShadowMap;
  66340. },
  66341. /**
  66342. * Sets the current filter is to VSM.
  66343. * DEPRECATED. Should use useExponentialShadowMap instead.
  66344. */
  66345. set: function (value) {
  66346. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66347. this.useExponentialShadowMap = value;
  66348. },
  66349. enumerable: true,
  66350. configurable: true
  66351. });
  66352. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66353. /**
  66354. * Gets if the current filter is set to blurred VSM.
  66355. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66356. */
  66357. get: function () {
  66358. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66359. return this.useBlurExponentialShadowMap;
  66360. },
  66361. /**
  66362. * Sets the current filter is to blurred VSM.
  66363. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66364. */
  66365. set: function (value) {
  66366. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66367. this.useBlurExponentialShadowMap = value;
  66368. },
  66369. enumerable: true,
  66370. configurable: true
  66371. });
  66372. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66373. /**
  66374. * Gets if the current filter is set to ESM.
  66375. */
  66376. get: function () {
  66377. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66378. },
  66379. /**
  66380. * Sets the current filter is to ESM.
  66381. */
  66382. set: function (value) {
  66383. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66384. return;
  66385. }
  66386. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66387. },
  66388. enumerable: true,
  66389. configurable: true
  66390. });
  66391. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66392. /**
  66393. * Gets if the current filter is set to filtered ESM.
  66394. */
  66395. get: function () {
  66396. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66397. },
  66398. /**
  66399. * Gets if the current filter is set to filtered ESM.
  66400. */
  66401. set: function (value) {
  66402. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66403. return;
  66404. }
  66405. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66411. /**
  66412. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66413. * exponential to prevent steep falloff artifacts).
  66414. */
  66415. get: function () {
  66416. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66417. },
  66418. /**
  66419. * Sets the current filter to "close ESM" (using the inverse of the
  66420. * exponential to prevent steep falloff artifacts).
  66421. */
  66422. set: function (value) {
  66423. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66424. return;
  66425. }
  66426. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66427. },
  66428. enumerable: true,
  66429. configurable: true
  66430. });
  66431. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66432. /**
  66433. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66434. * exponential to prevent steep falloff artifacts).
  66435. */
  66436. get: function () {
  66437. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66438. },
  66439. /**
  66440. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66441. * exponential to prevent steep falloff artifacts).
  66442. */
  66443. set: function (value) {
  66444. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66445. return;
  66446. }
  66447. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66453. /**
  66454. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66455. */
  66456. get: function () {
  66457. return this.filter === ShadowGenerator.FILTER_PCF;
  66458. },
  66459. /**
  66460. * Sets the current filter to "PCF" (percentage closer filtering).
  66461. */
  66462. set: function (value) {
  66463. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66464. return;
  66465. }
  66466. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66467. },
  66468. enumerable: true,
  66469. configurable: true
  66470. });
  66471. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66472. /**
  66473. * Gets the PCF or PCSS Quality.
  66474. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66475. */
  66476. get: function () {
  66477. return this._filteringQuality;
  66478. },
  66479. /**
  66480. * Sets the PCF or PCSS Quality.
  66481. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66482. */
  66483. set: function (filteringQuality) {
  66484. this._filteringQuality = filteringQuality;
  66485. },
  66486. enumerable: true,
  66487. configurable: true
  66488. });
  66489. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66490. /**
  66491. * Gets if the current filter is set to "PCSS" (contact hardening).
  66492. */
  66493. get: function () {
  66494. return this.filter === ShadowGenerator.FILTER_PCSS;
  66495. },
  66496. /**
  66497. * Sets the current filter to "PCSS" (contact hardening).
  66498. */
  66499. set: function (value) {
  66500. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66501. return;
  66502. }
  66503. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66504. },
  66505. enumerable: true,
  66506. configurable: true
  66507. });
  66508. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66509. /**
  66510. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66511. * Using a ratio helps keeping shape stability independently of the map size.
  66512. *
  66513. * It does not account for the light projection as it was having too much
  66514. * instability during the light setup or during light position changes.
  66515. *
  66516. * Only valid if useContactHardeningShadow is true.
  66517. */
  66518. get: function () {
  66519. return this._contactHardeningLightSizeUVRatio;
  66520. },
  66521. /**
  66522. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66523. * Using a ratio helps keeping shape stability independently of the map size.
  66524. *
  66525. * It does not account for the light projection as it was having too much
  66526. * instability during the light setup or during light position changes.
  66527. *
  66528. * Only valid if useContactHardeningShadow is true.
  66529. */
  66530. set: function (contactHardeningLightSizeUVRatio) {
  66531. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66532. },
  66533. enumerable: true,
  66534. configurable: true
  66535. });
  66536. /**
  66537. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66538. * 0 means strongest and 1 would means no shadow.
  66539. * @returns the darkness.
  66540. */
  66541. ShadowGenerator.prototype.getDarkness = function () {
  66542. return this._darkness;
  66543. };
  66544. /**
  66545. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66546. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66547. * @returns the shadow generator allowing fluent coding.
  66548. */
  66549. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66550. if (darkness >= 1.0)
  66551. this._darkness = 1.0;
  66552. else if (darkness <= 0.0)
  66553. this._darkness = 0.0;
  66554. else
  66555. this._darkness = darkness;
  66556. return this;
  66557. };
  66558. /**
  66559. * Sets the ability to have transparent shadow (boolean).
  66560. * @param transparent True if transparent else False
  66561. * @returns the shadow generator allowing fluent coding
  66562. */
  66563. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66564. this._transparencyShadow = transparent;
  66565. return this;
  66566. };
  66567. /**
  66568. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66569. * @returns The render target texture if present otherwise, null
  66570. */
  66571. ShadowGenerator.prototype.getShadowMap = function () {
  66572. return this._shadowMap;
  66573. };
  66574. /**
  66575. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66576. * @returns The render target texture if the shadow map is present otherwise, null
  66577. */
  66578. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66579. if (this._shadowMap2) {
  66580. return this._shadowMap2;
  66581. }
  66582. return this._shadowMap;
  66583. };
  66584. /**
  66585. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66586. * @param mesh Mesh to add
  66587. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66588. * @returns the Shadow Generator itself
  66589. */
  66590. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66591. if (includeDescendants === void 0) { includeDescendants = true; }
  66592. if (!this._shadowMap) {
  66593. return this;
  66594. }
  66595. if (!this._shadowMap.renderList) {
  66596. this._shadowMap.renderList = [];
  66597. }
  66598. this._shadowMap.renderList.push(mesh);
  66599. if (includeDescendants) {
  66600. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66601. }
  66602. return this;
  66603. var _a;
  66604. };
  66605. /**
  66606. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66607. * @param mesh Mesh to remove
  66608. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66609. * @returns the Shadow Generator itself
  66610. */
  66611. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66612. if (includeDescendants === void 0) { includeDescendants = true; }
  66613. if (!this._shadowMap || !this._shadowMap.renderList) {
  66614. return this;
  66615. }
  66616. var index = this._shadowMap.renderList.indexOf(mesh);
  66617. if (index !== -1) {
  66618. this._shadowMap.renderList.splice(index, 1);
  66619. }
  66620. if (includeDescendants) {
  66621. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66622. var child = _a[_i];
  66623. this.removeShadowCaster(child);
  66624. }
  66625. }
  66626. return this;
  66627. };
  66628. /**
  66629. * Returns the associated light object.
  66630. * @returns the light generating the shadow
  66631. */
  66632. ShadowGenerator.prototype.getLight = function () {
  66633. return this._light;
  66634. };
  66635. ShadowGenerator.prototype._initializeGenerator = function () {
  66636. this._light._markMeshesAsLightDirty();
  66637. this._initializeShadowMap();
  66638. };
  66639. ShadowGenerator.prototype._initializeShadowMap = function () {
  66640. var _this = this;
  66641. // Render target
  66642. var engine = this._scene.getEngine();
  66643. if (engine.webGLVersion > 1) {
  66644. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66645. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66646. }
  66647. else {
  66648. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66649. }
  66650. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66651. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66652. this._shadowMap.anisotropicFilteringLevel = 1;
  66653. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66654. this._shadowMap.renderParticles = false;
  66655. this._shadowMap.ignoreCameraViewport = true;
  66656. // Record Face Index before render.
  66657. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66658. _this._currentFaceIndex = faceIndex;
  66659. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66660. engine.setColorWrite(false);
  66661. }
  66662. });
  66663. // Custom render function.
  66664. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66665. // Blur if required afer render.
  66666. this._shadowMap.onAfterUnbindObservable.add(function () {
  66667. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66668. engine.setColorWrite(true);
  66669. }
  66670. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66671. return;
  66672. }
  66673. var shadowMap = _this.getShadowMapForRendering();
  66674. if (shadowMap) {
  66675. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66676. }
  66677. });
  66678. // Clear according to the chosen filter.
  66679. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66680. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66681. this._shadowMap.onClearObservable.add(function (engine) {
  66682. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66683. engine.clear(clearOne, false, true, false);
  66684. }
  66685. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66686. engine.clear(clearZero, true, true, false);
  66687. }
  66688. else {
  66689. engine.clear(clearOne, true, true, false);
  66690. }
  66691. });
  66692. };
  66693. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66694. var _this = this;
  66695. var engine = this._scene.getEngine();
  66696. var targetSize = this._mapSize / this.blurScale;
  66697. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66698. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66699. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66700. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66701. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66702. }
  66703. if (this.useKernelBlur) {
  66704. 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);
  66705. this._kernelBlurXPostprocess.width = targetSize;
  66706. this._kernelBlurXPostprocess.height = targetSize;
  66707. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66708. effect.setTexture("textureSampler", _this._shadowMap);
  66709. });
  66710. 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);
  66711. this._kernelBlurXPostprocess.autoClear = false;
  66712. this._kernelBlurYPostprocess.autoClear = false;
  66713. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66714. this._kernelBlurXPostprocess.packedFloat = true;
  66715. this._kernelBlurYPostprocess.packedFloat = true;
  66716. }
  66717. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66718. }
  66719. else {
  66720. 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);
  66721. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66722. effect.setFloat2("screenSize", targetSize, targetSize);
  66723. effect.setTexture("textureSampler", _this._shadowMap);
  66724. });
  66725. this._boxBlurPostprocess.autoClear = false;
  66726. this._blurPostProcesses = [this._boxBlurPostprocess];
  66727. }
  66728. };
  66729. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66730. var index;
  66731. var engine = this._scene.getEngine();
  66732. if (depthOnlySubMeshes.length) {
  66733. engine.setColorWrite(false);
  66734. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66735. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66736. }
  66737. engine.setColorWrite(true);
  66738. }
  66739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66740. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66741. }
  66742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66743. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66744. }
  66745. if (this._transparencyShadow) {
  66746. for (index = 0; index < transparentSubMeshes.length; index++) {
  66747. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66748. }
  66749. }
  66750. };
  66751. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66752. var _this = this;
  66753. var mesh = subMesh.getRenderingMesh();
  66754. var scene = this._scene;
  66755. var engine = scene.getEngine();
  66756. var material = subMesh.getMaterial();
  66757. if (!material) {
  66758. return;
  66759. }
  66760. // Culling
  66761. engine.setState(material.backFaceCulling);
  66762. // Managing instances
  66763. var batch = mesh._getInstancesRenderList(subMesh._id);
  66764. if (batch.mustReturn) {
  66765. return;
  66766. }
  66767. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66768. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66769. engine.enableEffect(this._effect);
  66770. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66771. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66772. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66773. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66774. this._effect.setVector3("lightData", this._cachedDirection);
  66775. }
  66776. else {
  66777. this._effect.setVector3("lightData", this._cachedPosition);
  66778. }
  66779. if (scene.activeCamera) {
  66780. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66781. }
  66782. // Alpha test
  66783. if (material && material.needAlphaTesting()) {
  66784. var alphaTexture = material.getAlphaTestTexture();
  66785. if (alphaTexture) {
  66786. this._effect.setTexture("diffuseSampler", alphaTexture);
  66787. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66788. }
  66789. }
  66790. // Bones
  66791. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66792. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66793. }
  66794. // Morph targets
  66795. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66796. if (this.forceBackFacesOnly) {
  66797. engine.setState(true, 0, false, true);
  66798. }
  66799. // Draw
  66800. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66801. if (this.forceBackFacesOnly) {
  66802. engine.setState(true, 0, false, false);
  66803. }
  66804. }
  66805. else {
  66806. // Need to reset refresh rate of the shadowMap
  66807. if (this._shadowMap) {
  66808. this._shadowMap.resetRefreshCounter();
  66809. }
  66810. }
  66811. };
  66812. ShadowGenerator.prototype._applyFilterValues = function () {
  66813. if (!this._shadowMap) {
  66814. return;
  66815. }
  66816. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66817. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66818. }
  66819. else {
  66820. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66821. }
  66822. };
  66823. /**
  66824. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66825. * @param onCompiled Callback triggered at the and of the effects compilation
  66826. * @param options Sets of optional options forcing the compilation with different modes
  66827. */
  66828. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66829. var _this = this;
  66830. var localOptions = __assign({ useInstances: false }, options);
  66831. var shadowMap = this.getShadowMap();
  66832. if (!shadowMap) {
  66833. if (onCompiled) {
  66834. onCompiled(this);
  66835. }
  66836. return;
  66837. }
  66838. var renderList = shadowMap.renderList;
  66839. if (!renderList) {
  66840. if (onCompiled) {
  66841. onCompiled(this);
  66842. }
  66843. return;
  66844. }
  66845. var subMeshes = new Array();
  66846. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66847. var mesh = renderList_1[_i];
  66848. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66849. }
  66850. if (subMeshes.length === 0) {
  66851. if (onCompiled) {
  66852. onCompiled(this);
  66853. }
  66854. return;
  66855. }
  66856. var currentIndex = 0;
  66857. var checkReady = function () {
  66858. if (!_this._scene || !_this._scene.getEngine()) {
  66859. return;
  66860. }
  66861. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66862. currentIndex++;
  66863. if (currentIndex >= subMeshes.length) {
  66864. if (onCompiled) {
  66865. onCompiled(_this);
  66866. }
  66867. return;
  66868. }
  66869. }
  66870. setTimeout(checkReady, 16);
  66871. };
  66872. checkReady();
  66873. };
  66874. /**
  66875. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66876. * @param options Sets of optional options forcing the compilation with different modes
  66877. * @returns A promise that resolves when the compilation completes
  66878. */
  66879. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66880. var _this = this;
  66881. return new Promise(function (resolve) {
  66882. _this.forceCompilation(function () {
  66883. resolve();
  66884. }, options);
  66885. });
  66886. };
  66887. /**
  66888. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66889. * @param subMesh The submesh we want to render in the shadow map
  66890. * @param useInstances Defines wether will draw in the map using instances
  66891. * @returns true if ready otherwise, false
  66892. */
  66893. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66894. var defines = [];
  66895. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66896. defines.push("#define FLOAT");
  66897. }
  66898. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66899. defines.push("#define ESM");
  66900. }
  66901. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66902. defines.push("#define DEPTHTEXTURE");
  66903. }
  66904. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66905. var mesh = subMesh.getMesh();
  66906. var material = subMesh.getMaterial();
  66907. // Normal bias.
  66908. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66909. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66910. defines.push("#define NORMAL");
  66911. if (mesh.nonUniformScaling) {
  66912. defines.push("#define NONUNIFORMSCALING");
  66913. }
  66914. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66915. defines.push("#define DIRECTIONINLIGHTDATA");
  66916. }
  66917. }
  66918. // Alpha test
  66919. if (material && material.needAlphaTesting()) {
  66920. var alphaTexture = material.getAlphaTestTexture();
  66921. if (alphaTexture) {
  66922. defines.push("#define ALPHATEST");
  66923. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66924. attribs.push(BABYLON.VertexBuffer.UVKind);
  66925. defines.push("#define UV1");
  66926. }
  66927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66928. if (alphaTexture.coordinatesIndex === 1) {
  66929. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66930. defines.push("#define UV2");
  66931. }
  66932. }
  66933. }
  66934. }
  66935. // Bones
  66936. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66939. if (mesh.numBoneInfluencers > 4) {
  66940. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66941. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66942. }
  66943. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66944. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66945. }
  66946. else {
  66947. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66948. }
  66949. // Morph targets
  66950. var manager = mesh.morphTargetManager;
  66951. var morphInfluencers = 0;
  66952. if (manager) {
  66953. if (manager.numInfluencers > 0) {
  66954. defines.push("#define MORPHTARGETS");
  66955. morphInfluencers = manager.numInfluencers;
  66956. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66957. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66958. }
  66959. }
  66960. // Instances
  66961. if (useInstances) {
  66962. defines.push("#define INSTANCES");
  66963. attribs.push("world0");
  66964. attribs.push("world1");
  66965. attribs.push("world2");
  66966. attribs.push("world3");
  66967. }
  66968. // Get correct effect
  66969. var join = defines.join("\n");
  66970. if (this._cachedDefines !== join) {
  66971. this._cachedDefines = join;
  66972. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66973. }
  66974. if (!this._effect.isReady()) {
  66975. return false;
  66976. }
  66977. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66978. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66979. this._initializeBlurRTTAndPostProcesses();
  66980. }
  66981. }
  66982. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66983. return false;
  66984. }
  66985. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66986. return false;
  66987. }
  66988. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66989. return false;
  66990. }
  66991. return true;
  66992. };
  66993. /**
  66994. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66995. * @param defines Defines of the material we want to update
  66996. * @param lightIndex Index of the light in the enabled light list of the material
  66997. */
  66998. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66999. var scene = this._scene;
  67000. var light = this._light;
  67001. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67002. return;
  67003. }
  67004. defines["SHADOW" + lightIndex] = true;
  67005. if (this.useContactHardeningShadow) {
  67006. defines["SHADOWPCSS" + lightIndex] = true;
  67007. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67008. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67009. }
  67010. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67011. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67012. }
  67013. // else default to high.
  67014. }
  67015. if (this.usePercentageCloserFiltering) {
  67016. defines["SHADOWPCF" + lightIndex] = true;
  67017. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67018. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67019. }
  67020. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67021. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67022. }
  67023. // else default to high.
  67024. }
  67025. else if (this.usePoissonSampling) {
  67026. defines["SHADOWPOISSON" + lightIndex] = true;
  67027. }
  67028. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67029. defines["SHADOWESM" + lightIndex] = true;
  67030. }
  67031. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67032. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67033. }
  67034. if (light.needCube()) {
  67035. defines["SHADOWCUBE" + lightIndex] = true;
  67036. }
  67037. };
  67038. /**
  67039. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67040. * defined in the generator but impacting the effect).
  67041. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67042. * @param effect The effect we are binfing the information for
  67043. */
  67044. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67045. var light = this._light;
  67046. var scene = this._scene;
  67047. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67048. return;
  67049. }
  67050. var camera = scene.activeCamera;
  67051. if (!camera) {
  67052. return;
  67053. }
  67054. var shadowMap = this.getShadowMap();
  67055. if (!shadowMap) {
  67056. return;
  67057. }
  67058. if (!light.needCube()) {
  67059. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67060. }
  67061. // Only PCF uses depth stencil texture.
  67062. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67063. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67064. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67065. }
  67066. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67067. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67068. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67069. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67070. }
  67071. else {
  67072. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67073. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67074. }
  67075. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67076. };
  67077. /**
  67078. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67079. * (eq to shadow prjection matrix * light transform matrix)
  67080. * @returns The transform matrix used to create the shadow map
  67081. */
  67082. ShadowGenerator.prototype.getTransformMatrix = function () {
  67083. var scene = this._scene;
  67084. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67085. return this._transformMatrix;
  67086. }
  67087. this._currentRenderID = scene.getRenderId();
  67088. this._currentFaceIndexCache = this._currentFaceIndex;
  67089. var lightPosition = this._light.position;
  67090. if (this._light.computeTransformedInformation()) {
  67091. lightPosition = this._light.transformedPosition;
  67092. }
  67093. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67094. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67095. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67096. }
  67097. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67098. this._cachedPosition.copyFrom(lightPosition);
  67099. this._cachedDirection.copyFrom(this._lightDirection);
  67100. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67101. var shadowMap = this.getShadowMap();
  67102. if (shadowMap) {
  67103. var renderList = shadowMap.renderList;
  67104. if (renderList) {
  67105. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67106. }
  67107. }
  67108. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67109. }
  67110. return this._transformMatrix;
  67111. };
  67112. /**
  67113. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67114. * Cube and 2D textures for instance.
  67115. */
  67116. ShadowGenerator.prototype.recreateShadowMap = function () {
  67117. var shadowMap = this._shadowMap;
  67118. if (!shadowMap) {
  67119. return;
  67120. }
  67121. // Track render list.
  67122. var renderList = shadowMap.renderList;
  67123. // Clean up existing data.
  67124. this._disposeRTTandPostProcesses();
  67125. // Reinitializes.
  67126. this._initializeGenerator();
  67127. // Reaffect the filter to ensure a correct fallback if necessary.
  67128. this.filter = this.filter;
  67129. // Reaffect the filter.
  67130. this._applyFilterValues();
  67131. // Reaffect Render List.
  67132. this._shadowMap.renderList = renderList;
  67133. };
  67134. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67135. if (this._shadowMap2) {
  67136. this._shadowMap2.dispose();
  67137. this._shadowMap2 = null;
  67138. }
  67139. if (this._boxBlurPostprocess) {
  67140. this._boxBlurPostprocess.dispose();
  67141. this._boxBlurPostprocess = null;
  67142. }
  67143. if (this._kernelBlurXPostprocess) {
  67144. this._kernelBlurXPostprocess.dispose();
  67145. this._kernelBlurXPostprocess = null;
  67146. }
  67147. if (this._kernelBlurYPostprocess) {
  67148. this._kernelBlurYPostprocess.dispose();
  67149. this._kernelBlurYPostprocess = null;
  67150. }
  67151. this._blurPostProcesses = [];
  67152. };
  67153. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67154. if (this._shadowMap) {
  67155. this._shadowMap.dispose();
  67156. this._shadowMap = null;
  67157. }
  67158. this._disposeBlurPostProcesses();
  67159. };
  67160. /**
  67161. * Disposes the ShadowGenerator.
  67162. * Returns nothing.
  67163. */
  67164. ShadowGenerator.prototype.dispose = function () {
  67165. this._disposeRTTandPostProcesses();
  67166. if (this._light) {
  67167. this._light._shadowGenerator = null;
  67168. this._light._markMeshesAsLightDirty();
  67169. }
  67170. };
  67171. /**
  67172. * Serializes the shadow generator setup to a json object.
  67173. * @returns The serialized JSON object
  67174. */
  67175. ShadowGenerator.prototype.serialize = function () {
  67176. var serializationObject = {};
  67177. var shadowMap = this.getShadowMap();
  67178. if (!shadowMap) {
  67179. return serializationObject;
  67180. }
  67181. serializationObject.lightId = this._light.id;
  67182. serializationObject.mapSize = shadowMap.getRenderSize();
  67183. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67184. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67185. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67186. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67187. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67188. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67189. serializationObject.depthScale = this.depthScale;
  67190. serializationObject.darkness = this.getDarkness();
  67191. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67192. serializationObject.blurKernel = this.blurKernel;
  67193. serializationObject.blurScale = this.blurScale;
  67194. serializationObject.useKernelBlur = this.useKernelBlur;
  67195. serializationObject.transparencyShadow = this._transparencyShadow;
  67196. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67197. serializationObject.bias = this.bias;
  67198. serializationObject.normalBias = this.normalBias;
  67199. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67200. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67201. serializationObject.filteringQuality = this.filteringQuality;
  67202. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67203. serializationObject.renderList = [];
  67204. if (shadowMap.renderList) {
  67205. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67206. var mesh = shadowMap.renderList[meshIndex];
  67207. serializationObject.renderList.push(mesh.id);
  67208. }
  67209. }
  67210. return serializationObject;
  67211. };
  67212. /**
  67213. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67214. * @param parsedShadowGenerator The JSON object to parse
  67215. * @param scene The scene to create the shadow map for
  67216. * @returns The parsed shadow generator
  67217. */
  67218. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67219. //casting to point light, as light is missing the position attr and typescript complains.
  67220. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67221. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67222. var shadowMap = shadowGenerator.getShadowMap();
  67223. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67224. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67225. meshes.forEach(function (mesh) {
  67226. if (!shadowMap) {
  67227. return;
  67228. }
  67229. if (!shadowMap.renderList) {
  67230. shadowMap.renderList = [];
  67231. }
  67232. shadowMap.renderList.push(mesh);
  67233. });
  67234. }
  67235. if (parsedShadowGenerator.usePoissonSampling) {
  67236. shadowGenerator.usePoissonSampling = true;
  67237. }
  67238. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67239. shadowGenerator.useExponentialShadowMap = true;
  67240. }
  67241. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67242. shadowGenerator.useBlurExponentialShadowMap = true;
  67243. }
  67244. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67245. shadowGenerator.useCloseExponentialShadowMap = true;
  67246. }
  67247. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67248. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67249. }
  67250. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67251. shadowGenerator.usePercentageCloserFiltering = true;
  67252. }
  67253. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67254. shadowGenerator.useContactHardeningShadow = true;
  67255. }
  67256. if (parsedShadowGenerator.filteringQuality) {
  67257. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67258. }
  67259. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67260. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67261. }
  67262. // Backward compat
  67263. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67264. shadowGenerator.useExponentialShadowMap = true;
  67265. }
  67266. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67267. shadowGenerator.useBlurExponentialShadowMap = true;
  67268. }
  67269. if (parsedShadowGenerator.depthScale) {
  67270. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67271. }
  67272. if (parsedShadowGenerator.blurScale) {
  67273. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67274. }
  67275. if (parsedShadowGenerator.blurBoxOffset) {
  67276. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67277. }
  67278. if (parsedShadowGenerator.useKernelBlur) {
  67279. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67280. }
  67281. if (parsedShadowGenerator.blurKernel) {
  67282. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67283. }
  67284. if (parsedShadowGenerator.bias !== undefined) {
  67285. shadowGenerator.bias = parsedShadowGenerator.bias;
  67286. }
  67287. if (parsedShadowGenerator.normalBias !== undefined) {
  67288. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67289. }
  67290. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67291. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67292. }
  67293. if (parsedShadowGenerator.darkness) {
  67294. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67295. }
  67296. if (parsedShadowGenerator.transparencyShadow) {
  67297. shadowGenerator.setTransparencyShadow(true);
  67298. }
  67299. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67300. return shadowGenerator;
  67301. };
  67302. /**
  67303. * Shadow generator mode None: no filtering applied.
  67304. */
  67305. ShadowGenerator.FILTER_NONE = 0;
  67306. /**
  67307. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67308. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67309. */
  67310. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67311. /**
  67312. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67313. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67314. */
  67315. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67316. /**
  67317. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67318. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67319. */
  67320. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67321. /**
  67322. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67323. * edge artifacts on steep falloff.
  67324. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67325. */
  67326. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67327. /**
  67328. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67329. * edge artifacts on steep falloff.
  67330. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67331. */
  67332. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67333. /**
  67334. * Shadow generator mode PCF: Percentage Closer Filtering
  67335. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67336. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67337. */
  67338. ShadowGenerator.FILTER_PCF = 6;
  67339. /**
  67340. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67341. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67342. * Contact Hardening
  67343. */
  67344. ShadowGenerator.FILTER_PCSS = 7;
  67345. /**
  67346. * Reserved for PCF and PCSS
  67347. * Highest Quality.
  67348. *
  67349. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67350. *
  67351. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67352. */
  67353. ShadowGenerator.QUALITY_HIGH = 0;
  67354. /**
  67355. * Reserved for PCF and PCSS
  67356. * Good tradeoff for quality/perf cross devices
  67357. *
  67358. * Execute PCF on a 3*3 kernel.
  67359. *
  67360. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67361. */
  67362. ShadowGenerator.QUALITY_MEDIUM = 1;
  67363. /**
  67364. * Reserved for PCF and PCSS
  67365. * The lowest quality but the fastest.
  67366. *
  67367. * Execute PCF on a 1*1 kernel.
  67368. *
  67369. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67370. */
  67371. ShadowGenerator.QUALITY_LOW = 2;
  67372. return ShadowGenerator;
  67373. }());
  67374. BABYLON.ShadowGenerator = ShadowGenerator;
  67375. })(BABYLON || (BABYLON = {}));
  67376. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67377. var BABYLON;
  67378. (function (BABYLON) {
  67379. var DefaultLoadingScreen = /** @class */ (function () {
  67380. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67381. if (_loadingText === void 0) { _loadingText = ""; }
  67382. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67383. var _this = this;
  67384. this._renderingCanvas = _renderingCanvas;
  67385. this._loadingText = _loadingText;
  67386. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67387. // Resize
  67388. this._resizeLoadingUI = function () {
  67389. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67390. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67391. if (!_this._loadingDiv) {
  67392. return;
  67393. }
  67394. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67395. _this._loadingDiv.style.left = canvasRect.left + "px";
  67396. _this._loadingDiv.style.top = canvasRect.top + "px";
  67397. _this._loadingDiv.style.width = canvasRect.width + "px";
  67398. _this._loadingDiv.style.height = canvasRect.height + "px";
  67399. };
  67400. }
  67401. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67402. if (this._loadingDiv) {
  67403. // Do not add a loading screen if there is already one
  67404. return;
  67405. }
  67406. this._loadingDiv = document.createElement("div");
  67407. this._loadingDiv.id = "babylonjsLoadingDiv";
  67408. this._loadingDiv.style.opacity = "0";
  67409. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67410. this._loadingDiv.style.pointerEvents = "none";
  67411. // Loading text
  67412. this._loadingTextDiv = document.createElement("div");
  67413. this._loadingTextDiv.style.position = "absolute";
  67414. this._loadingTextDiv.style.left = "0";
  67415. this._loadingTextDiv.style.top = "50%";
  67416. this._loadingTextDiv.style.marginTop = "80px";
  67417. this._loadingTextDiv.style.width = "100%";
  67418. this._loadingTextDiv.style.height = "20px";
  67419. this._loadingTextDiv.style.fontFamily = "Arial";
  67420. this._loadingTextDiv.style.fontSize = "14px";
  67421. this._loadingTextDiv.style.color = "white";
  67422. this._loadingTextDiv.style.textAlign = "center";
  67423. this._loadingTextDiv.innerHTML = "Loading";
  67424. this._loadingDiv.appendChild(this._loadingTextDiv);
  67425. //set the predefined text
  67426. this._loadingTextDiv.innerHTML = this._loadingText;
  67427. // Generating keyframes
  67428. var style = document.createElement('style');
  67429. style.type = 'text/css';
  67430. 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 }";
  67431. style.innerHTML = keyFrames;
  67432. document.getElementsByTagName('head')[0].appendChild(style);
  67433. // Loading img
  67434. var imgBack = new Image();
  67435. 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";
  67436. imgBack.style.position = "absolute";
  67437. imgBack.style.left = "50%";
  67438. imgBack.style.top = "50%";
  67439. imgBack.style.marginLeft = "-60px";
  67440. imgBack.style.marginTop = "-60px";
  67441. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67442. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67443. imgBack.style.transformOrigin = "50% 50%";
  67444. imgBack.style.webkitTransformOrigin = "50% 50%";
  67445. this._loadingDiv.appendChild(imgBack);
  67446. this._resizeLoadingUI();
  67447. window.addEventListener("resize", this._resizeLoadingUI);
  67448. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67449. document.body.appendChild(this._loadingDiv);
  67450. this._loadingDiv.style.opacity = "1";
  67451. };
  67452. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67453. var _this = this;
  67454. if (!this._loadingDiv) {
  67455. return;
  67456. }
  67457. var onTransitionEnd = function () {
  67458. if (!_this._loadingDiv) {
  67459. return;
  67460. }
  67461. document.body.removeChild(_this._loadingDiv);
  67462. window.removeEventListener("resize", _this._resizeLoadingUI);
  67463. _this._loadingDiv = null;
  67464. };
  67465. this._loadingDiv.style.opacity = "0";
  67466. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67467. };
  67468. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67469. set: function (text) {
  67470. this._loadingText = text;
  67471. if (this._loadingTextDiv) {
  67472. this._loadingTextDiv.innerHTML = this._loadingText;
  67473. }
  67474. },
  67475. enumerable: true,
  67476. configurable: true
  67477. });
  67478. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67479. get: function () {
  67480. return this._loadingDivBackgroundColor;
  67481. },
  67482. set: function (color) {
  67483. this._loadingDivBackgroundColor = color;
  67484. if (!this._loadingDiv) {
  67485. return;
  67486. }
  67487. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67488. },
  67489. enumerable: true,
  67490. configurable: true
  67491. });
  67492. return DefaultLoadingScreen;
  67493. }());
  67494. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67495. })(BABYLON || (BABYLON = {}));
  67496. //# sourceMappingURL=babylon.loadingScreen.js.map
  67497. var BABYLON;
  67498. (function (BABYLON) {
  67499. var SceneLoaderProgressEvent = /** @class */ (function () {
  67500. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67501. this.lengthComputable = lengthComputable;
  67502. this.loaded = loaded;
  67503. this.total = total;
  67504. }
  67505. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67506. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67507. };
  67508. return SceneLoaderProgressEvent;
  67509. }());
  67510. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67511. var SceneLoader = /** @class */ (function () {
  67512. function SceneLoader() {
  67513. }
  67514. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67515. get: function () {
  67516. return 0;
  67517. },
  67518. enumerable: true,
  67519. configurable: true
  67520. });
  67521. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67522. get: function () {
  67523. return 1;
  67524. },
  67525. enumerable: true,
  67526. configurable: true
  67527. });
  67528. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67529. get: function () {
  67530. return 2;
  67531. },
  67532. enumerable: true,
  67533. configurable: true
  67534. });
  67535. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67536. get: function () {
  67537. return 3;
  67538. },
  67539. enumerable: true,
  67540. configurable: true
  67541. });
  67542. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67543. get: function () {
  67544. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67545. },
  67546. set: function (value) {
  67547. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67548. },
  67549. enumerable: true,
  67550. configurable: true
  67551. });
  67552. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67553. get: function () {
  67554. return SceneLoader._ShowLoadingScreen;
  67555. },
  67556. set: function (value) {
  67557. SceneLoader._ShowLoadingScreen = value;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. Object.defineProperty(SceneLoader, "loggingLevel", {
  67563. get: function () {
  67564. return SceneLoader._loggingLevel;
  67565. },
  67566. set: function (value) {
  67567. SceneLoader._loggingLevel = value;
  67568. },
  67569. enumerable: true,
  67570. configurable: true
  67571. });
  67572. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67573. get: function () {
  67574. return SceneLoader._CleanBoneMatrixWeights;
  67575. },
  67576. set: function (value) {
  67577. SceneLoader._CleanBoneMatrixWeights = value;
  67578. },
  67579. enumerable: true,
  67580. configurable: true
  67581. });
  67582. SceneLoader._getDefaultPlugin = function () {
  67583. return SceneLoader._registeredPlugins[".babylon"];
  67584. };
  67585. SceneLoader._getPluginForExtension = function (extension) {
  67586. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67587. if (registeredPlugin) {
  67588. return registeredPlugin;
  67589. }
  67590. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67591. return SceneLoader._getDefaultPlugin();
  67592. };
  67593. SceneLoader._getPluginForDirectLoad = function (data) {
  67594. for (var extension in SceneLoader._registeredPlugins) {
  67595. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67596. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67597. return SceneLoader._registeredPlugins[extension];
  67598. }
  67599. }
  67600. return SceneLoader._getDefaultPlugin();
  67601. };
  67602. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67603. if (sceneFilename.name) {
  67604. sceneFilename = sceneFilename.name;
  67605. }
  67606. var queryStringPosition = sceneFilename.indexOf("?");
  67607. if (queryStringPosition !== -1) {
  67608. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67609. }
  67610. var dotPosition = sceneFilename.lastIndexOf(".");
  67611. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67612. return SceneLoader._getPluginForExtension(extension);
  67613. };
  67614. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67615. SceneLoader._getDirectLoad = function (sceneFilename) {
  67616. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67617. return sceneFilename.substr(5);
  67618. }
  67619. return null;
  67620. };
  67621. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67622. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67623. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67624. var plugin;
  67625. if (registeredPlugin.plugin.createPlugin) {
  67626. plugin = registeredPlugin.plugin.createPlugin();
  67627. }
  67628. else {
  67629. plugin = registeredPlugin.plugin;
  67630. }
  67631. var useArrayBuffer = registeredPlugin.isBinary;
  67632. var database;
  67633. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67634. var dataCallback = function (data, responseURL) {
  67635. if (scene.isDisposed) {
  67636. onError("Scene has been disposed");
  67637. return;
  67638. }
  67639. scene.database = database;
  67640. onSuccess(plugin, data, responseURL);
  67641. };
  67642. var request = null;
  67643. var pluginDisposed = false;
  67644. var onDisposeObservable = plugin.onDisposeObservable;
  67645. if (onDisposeObservable) {
  67646. onDisposeObservable.add(function () {
  67647. pluginDisposed = true;
  67648. if (request) {
  67649. request.abort();
  67650. request = null;
  67651. }
  67652. onDispose();
  67653. });
  67654. }
  67655. var manifestChecked = function () {
  67656. if (pluginDisposed) {
  67657. return;
  67658. }
  67659. var url = rootUrl + sceneFilename;
  67660. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67661. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67662. } : undefined, database, useArrayBuffer, function (request, exception) {
  67663. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67664. });
  67665. };
  67666. if (directLoad) {
  67667. dataCallback(directLoad);
  67668. return plugin;
  67669. }
  67670. if (rootUrl.indexOf("file:") === -1) {
  67671. var engine = scene.getEngine();
  67672. var canUseOfflineSupport = engine.enableOfflineSupport;
  67673. if (canUseOfflineSupport) {
  67674. // Also check for exceptions
  67675. var exceptionFound = false;
  67676. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67677. var regex = _a[_i];
  67678. if (regex.test(rootUrl + sceneFilename)) {
  67679. exceptionFound = true;
  67680. break;
  67681. }
  67682. }
  67683. canUseOfflineSupport = !exceptionFound;
  67684. }
  67685. if (canUseOfflineSupport) {
  67686. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67687. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67688. }
  67689. else {
  67690. manifestChecked();
  67691. }
  67692. }
  67693. // Loading file from disk via input file or drag'n'drop
  67694. else {
  67695. var fileOrString = sceneFilename;
  67696. if (fileOrString.name) { // File
  67697. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67698. }
  67699. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67700. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67701. }
  67702. else {
  67703. onError("Unable to find file named " + sceneFilename);
  67704. }
  67705. }
  67706. return plugin;
  67707. };
  67708. // Public functions
  67709. SceneLoader.GetPluginForExtension = function (extension) {
  67710. return SceneLoader._getPluginForExtension(extension).plugin;
  67711. };
  67712. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67713. return !!SceneLoader._registeredPlugins[extension];
  67714. };
  67715. SceneLoader.RegisterPlugin = function (plugin) {
  67716. if (typeof plugin.extensions === "string") {
  67717. var extension = plugin.extensions;
  67718. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67719. plugin: plugin,
  67720. isBinary: false
  67721. };
  67722. }
  67723. else {
  67724. var extensions = plugin.extensions;
  67725. Object.keys(extensions).forEach(function (extension) {
  67726. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67727. plugin: plugin,
  67728. isBinary: extensions[extension].isBinary
  67729. };
  67730. });
  67731. }
  67732. };
  67733. /**
  67734. * Import meshes into a scene
  67735. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67736. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67737. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67738. * @param scene the instance of BABYLON.Scene to append to
  67739. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67740. * @param onProgress a callback with a progress event for each file being loaded
  67741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67742. * @param pluginExtension the extension used to determine the plugin
  67743. * @returns The loaded plugin
  67744. */
  67745. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67746. if (sceneFilename === void 0) { sceneFilename = ""; }
  67747. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67748. if (onSuccess === void 0) { onSuccess = null; }
  67749. if (onProgress === void 0) { onProgress = null; }
  67750. if (onError === void 0) { onError = null; }
  67751. if (pluginExtension === void 0) { pluginExtension = null; }
  67752. if (!scene) {
  67753. BABYLON.Tools.Error("No scene available to import mesh to");
  67754. return null;
  67755. }
  67756. if (!sceneFilename) {
  67757. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67758. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67759. }
  67760. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67761. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67762. return null;
  67763. }
  67764. var loadingToken = {};
  67765. scene._addPendingData(loadingToken);
  67766. var disposeHandler = function () {
  67767. scene._removePendingData(loadingToken);
  67768. };
  67769. var errorHandler = function (message, exception) {
  67770. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67771. if (onError) {
  67772. onError(scene, errorMessage, exception);
  67773. }
  67774. else {
  67775. BABYLON.Tools.Error(errorMessage);
  67776. // should the exception be thrown?
  67777. }
  67778. disposeHandler();
  67779. };
  67780. var progressHandler = onProgress ? function (event) {
  67781. try {
  67782. onProgress(event);
  67783. }
  67784. catch (e) {
  67785. errorHandler("Error in onProgress callback", e);
  67786. }
  67787. } : undefined;
  67788. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67789. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67790. if (onSuccess) {
  67791. try {
  67792. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67793. }
  67794. catch (e) {
  67795. errorHandler("Error in onSuccess callback", e);
  67796. }
  67797. }
  67798. scene._removePendingData(loadingToken);
  67799. };
  67800. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67801. if (plugin.rewriteRootURL) {
  67802. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67803. }
  67804. if (sceneFilename === "") {
  67805. if (sceneFilename === "") {
  67806. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67807. }
  67808. }
  67809. if (plugin.importMesh) {
  67810. var syncedPlugin = plugin;
  67811. var meshes = new Array();
  67812. var particleSystems = new Array();
  67813. var skeletons = new Array();
  67814. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67815. return;
  67816. }
  67817. scene.loadingPluginName = plugin.name;
  67818. successHandler(meshes, particleSystems, skeletons, []);
  67819. }
  67820. else {
  67821. var asyncedPlugin = plugin;
  67822. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67823. scene.loadingPluginName = plugin.name;
  67824. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67825. }).catch(function (error) {
  67826. errorHandler(error.message, error);
  67827. });
  67828. }
  67829. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67830. };
  67831. /**
  67832. * Import meshes into a scene
  67833. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67834. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67835. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67836. * @param scene the instance of BABYLON.Scene to append to
  67837. * @param onProgress a callback with a progress event for each file being loaded
  67838. * @param pluginExtension the extension used to determine the plugin
  67839. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67840. */
  67841. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67842. if (sceneFilename === void 0) { sceneFilename = ""; }
  67843. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67844. if (onProgress === void 0) { onProgress = null; }
  67845. if (pluginExtension === void 0) { pluginExtension = null; }
  67846. return new Promise(function (resolve, reject) {
  67847. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67848. resolve({
  67849. meshes: meshes,
  67850. particleSystems: particleSystems,
  67851. skeletons: skeletons,
  67852. animationGroups: animationGroups
  67853. });
  67854. }, onProgress, function (scene, message, exception) {
  67855. reject(exception || new Error(message));
  67856. }, pluginExtension);
  67857. });
  67858. };
  67859. /**
  67860. * Load a scene
  67861. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67862. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67863. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67864. * @param onSuccess a callback with the scene when import succeeds
  67865. * @param onProgress a callback with a progress event for each file being loaded
  67866. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67867. * @param pluginExtension the extension used to determine the plugin
  67868. * @returns The loaded plugin
  67869. */
  67870. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67871. if (onSuccess === void 0) { onSuccess = null; }
  67872. if (onProgress === void 0) { onProgress = null; }
  67873. if (onError === void 0) { onError = null; }
  67874. if (pluginExtension === void 0) { pluginExtension = null; }
  67875. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67876. };
  67877. /**
  67878. * Load a scene
  67879. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67880. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67881. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67882. * @param onProgress a callback with a progress event for each file being loaded
  67883. * @param pluginExtension the extension used to determine the plugin
  67884. * @returns The loaded scene
  67885. */
  67886. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67887. if (onProgress === void 0) { onProgress = null; }
  67888. if (pluginExtension === void 0) { pluginExtension = null; }
  67889. return new Promise(function (resolve, reject) {
  67890. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67891. resolve(scene);
  67892. }, onProgress, function (scene, message, exception) {
  67893. reject(exception || new Error(message));
  67894. }, pluginExtension);
  67895. });
  67896. };
  67897. /**
  67898. * Append a scene
  67899. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67900. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67901. * @param scene is the instance of BABYLON.Scene to append to
  67902. * @param onSuccess a callback with the scene when import succeeds
  67903. * @param onProgress a callback with a progress event for each file being loaded
  67904. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67905. * @param pluginExtension the extension used to determine the plugin
  67906. * @returns The loaded plugin
  67907. */
  67908. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67909. if (sceneFilename === void 0) { sceneFilename = ""; }
  67910. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67911. if (onSuccess === void 0) { onSuccess = null; }
  67912. if (onProgress === void 0) { onProgress = null; }
  67913. if (onError === void 0) { onError = null; }
  67914. if (pluginExtension === void 0) { pluginExtension = null; }
  67915. if (!scene) {
  67916. BABYLON.Tools.Error("No scene available to append to");
  67917. return null;
  67918. }
  67919. if (!sceneFilename) {
  67920. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67921. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67922. }
  67923. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67924. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67925. return null;
  67926. }
  67927. if (SceneLoader.ShowLoadingScreen) {
  67928. scene.getEngine().displayLoadingUI();
  67929. }
  67930. var loadingToken = {};
  67931. scene._addPendingData(loadingToken);
  67932. var disposeHandler = function () {
  67933. scene._removePendingData(loadingToken);
  67934. scene.getEngine().hideLoadingUI();
  67935. };
  67936. var errorHandler = function (message, exception) {
  67937. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67938. if (onError) {
  67939. onError(scene, errorMessage, exception);
  67940. }
  67941. else {
  67942. BABYLON.Tools.Error(errorMessage);
  67943. // should the exception be thrown?
  67944. }
  67945. disposeHandler();
  67946. };
  67947. var progressHandler = onProgress ? function (event) {
  67948. try {
  67949. onProgress(event);
  67950. }
  67951. catch (e) {
  67952. errorHandler("Error in onProgress callback", e);
  67953. }
  67954. } : undefined;
  67955. var successHandler = function () {
  67956. if (onSuccess) {
  67957. try {
  67958. onSuccess(scene);
  67959. }
  67960. catch (e) {
  67961. errorHandler("Error in onSuccess callback", e);
  67962. }
  67963. }
  67964. scene._removePendingData(loadingToken);
  67965. };
  67966. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67967. if (sceneFilename === "") {
  67968. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67969. }
  67970. if (plugin.load) {
  67971. var syncedPlugin = plugin;
  67972. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67973. return;
  67974. }
  67975. scene.loadingPluginName = plugin.name;
  67976. successHandler();
  67977. }
  67978. else {
  67979. var asyncedPlugin = plugin;
  67980. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67981. scene.loadingPluginName = plugin.name;
  67982. successHandler();
  67983. }).catch(function (error) {
  67984. errorHandler(error.message, error);
  67985. });
  67986. }
  67987. if (SceneLoader.ShowLoadingScreen) {
  67988. scene.executeWhenReady(function () {
  67989. scene.getEngine().hideLoadingUI();
  67990. });
  67991. }
  67992. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67993. };
  67994. /**
  67995. * Append a scene
  67996. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67997. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67998. * @param scene is the instance of BABYLON.Scene to append to
  67999. * @param onProgress a callback with a progress event for each file being loaded
  68000. * @param pluginExtension the extension used to determine the plugin
  68001. * @returns The given scene
  68002. */
  68003. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68004. if (sceneFilename === void 0) { sceneFilename = ""; }
  68005. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68006. if (onProgress === void 0) { onProgress = null; }
  68007. if (pluginExtension === void 0) { pluginExtension = null; }
  68008. return new Promise(function (resolve, reject) {
  68009. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68010. resolve(scene);
  68011. }, onProgress, function (scene, message, exception) {
  68012. reject(exception || new Error(message));
  68013. }, pluginExtension);
  68014. });
  68015. };
  68016. /**
  68017. * Load a scene into an asset container
  68018. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68019. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68020. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68021. * @param onSuccess a callback with the scene when import succeeds
  68022. * @param onProgress a callback with a progress event for each file being loaded
  68023. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68024. * @param pluginExtension the extension used to determine the plugin
  68025. * @returns The loaded plugin
  68026. */
  68027. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68028. if (sceneFilename === void 0) { sceneFilename = ""; }
  68029. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68030. if (onSuccess === void 0) { onSuccess = null; }
  68031. if (onProgress === void 0) { onProgress = null; }
  68032. if (onError === void 0) { onError = null; }
  68033. if (pluginExtension === void 0) { pluginExtension = null; }
  68034. if (!scene) {
  68035. BABYLON.Tools.Error("No scene available to load asset container to");
  68036. return null;
  68037. }
  68038. if (!sceneFilename) {
  68039. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68040. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68041. }
  68042. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68043. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68044. return null;
  68045. }
  68046. var loadingToken = {};
  68047. scene._addPendingData(loadingToken);
  68048. var disposeHandler = function () {
  68049. scene._removePendingData(loadingToken);
  68050. };
  68051. var errorHandler = function (message, exception) {
  68052. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68053. if (onError) {
  68054. onError(scene, errorMessage, exception);
  68055. }
  68056. else {
  68057. BABYLON.Tools.Error(errorMessage);
  68058. // should the exception be thrown?
  68059. }
  68060. disposeHandler();
  68061. };
  68062. var progressHandler = onProgress ? function (event) {
  68063. try {
  68064. onProgress(event);
  68065. }
  68066. catch (e) {
  68067. errorHandler("Error in onProgress callback", e);
  68068. }
  68069. } : undefined;
  68070. var successHandler = function (assets) {
  68071. if (onSuccess) {
  68072. try {
  68073. onSuccess(assets);
  68074. }
  68075. catch (e) {
  68076. errorHandler("Error in onSuccess callback", e);
  68077. }
  68078. }
  68079. scene._removePendingData(loadingToken);
  68080. };
  68081. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68082. if (plugin.loadAssetContainer) {
  68083. var syncedPlugin = plugin;
  68084. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68085. if (!assetContainer) {
  68086. return;
  68087. }
  68088. scene.loadingPluginName = plugin.name;
  68089. successHandler(assetContainer);
  68090. }
  68091. else if (plugin.loadAssetContainerAsync) {
  68092. var asyncedPlugin = plugin;
  68093. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68094. scene.loadingPluginName = plugin.name;
  68095. successHandler(assetContainer);
  68096. }).catch(function (error) {
  68097. errorHandler(error.message, error);
  68098. });
  68099. }
  68100. else {
  68101. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68102. }
  68103. if (SceneLoader.ShowLoadingScreen) {
  68104. scene.executeWhenReady(function () {
  68105. scene.getEngine().hideLoadingUI();
  68106. });
  68107. }
  68108. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68109. };
  68110. /**
  68111. * Load a scene into an asset container
  68112. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68113. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68114. * @param scene is the instance of BABYLON.Scene to append to
  68115. * @param onProgress a callback with a progress event for each file being loaded
  68116. * @param pluginExtension the extension used to determine the plugin
  68117. * @returns The loaded asset container
  68118. */
  68119. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68120. if (sceneFilename === void 0) { sceneFilename = ""; }
  68121. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68122. if (onProgress === void 0) { onProgress = null; }
  68123. if (pluginExtension === void 0) { pluginExtension = null; }
  68124. return new Promise(function (resolve, reject) {
  68125. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68126. resolve(assetContainer);
  68127. }, onProgress, function (scene, message, exception) {
  68128. reject(exception || new Error(message));
  68129. }, pluginExtension);
  68130. });
  68131. };
  68132. // Flags
  68133. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68134. SceneLoader._ShowLoadingScreen = true;
  68135. SceneLoader._CleanBoneMatrixWeights = false;
  68136. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68137. // Members
  68138. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68139. SceneLoader._registeredPlugins = {};
  68140. return SceneLoader;
  68141. }());
  68142. BABYLON.SceneLoader = SceneLoader;
  68143. ;
  68144. })(BABYLON || (BABYLON = {}));
  68145. //# sourceMappingURL=babylon.sceneLoader.js.map
  68146. var BABYLON;
  68147. (function (BABYLON) {
  68148. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68149. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68150. var parsedMaterial = parsedData.materials[index];
  68151. if (parsedMaterial.id === id) {
  68152. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68153. }
  68154. }
  68155. return null;
  68156. };
  68157. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68158. for (var i in names) {
  68159. if (mesh.name === names[i]) {
  68160. hierarchyIds.push(mesh.id);
  68161. return true;
  68162. }
  68163. }
  68164. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68165. hierarchyIds.push(mesh.id);
  68166. return true;
  68167. }
  68168. return false;
  68169. };
  68170. var logOperation = function (operation, producer) {
  68171. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68172. };
  68173. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68174. if (addToScene === void 0) { addToScene = false; }
  68175. var container = new BABYLON.AssetContainer(scene);
  68176. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68177. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68178. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68179. // and avoid problems with multiple concurrent .babylon loads.
  68180. var log = "importScene has failed JSON parse";
  68181. try {
  68182. var parsedData = JSON.parse(data);
  68183. log = "";
  68184. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68185. var index;
  68186. var cache;
  68187. // Lights
  68188. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68189. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68190. var parsedLight = parsedData.lights[index];
  68191. var light = BABYLON.Light.Parse(parsedLight, scene);
  68192. if (light) {
  68193. container.lights.push(light);
  68194. log += (index === 0 ? "\n\tLights:" : "");
  68195. log += "\n\t\t" + light.toString(fullDetails);
  68196. }
  68197. }
  68198. }
  68199. // Animations
  68200. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68201. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68202. var parsedAnimation = parsedData.animations[index];
  68203. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68204. scene.animations.push(animation);
  68205. container.animations.push(animation);
  68206. log += (index === 0 ? "\n\tAnimations:" : "");
  68207. log += "\n\t\t" + animation.toString(fullDetails);
  68208. }
  68209. }
  68210. // Materials
  68211. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68212. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68213. var parsedMaterial = parsedData.materials[index];
  68214. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68215. container.materials.push(mat);
  68216. log += (index === 0 ? "\n\tMaterials:" : "");
  68217. log += "\n\t\t" + mat.toString(fullDetails);
  68218. }
  68219. }
  68220. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68221. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68222. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68223. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68224. container.multiMaterials.push(mmat);
  68225. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68226. log += "\n\t\t" + mmat.toString(fullDetails);
  68227. }
  68228. }
  68229. // Morph targets
  68230. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68231. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68232. var managerData = _a[_i];
  68233. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68234. }
  68235. }
  68236. // Skeletons
  68237. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68238. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68239. var parsedSkeleton = parsedData.skeletons[index];
  68240. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68241. container.skeletons.push(skeleton);
  68242. log += (index === 0 ? "\n\tSkeletons:" : "");
  68243. log += "\n\t\t" + skeleton.toString(fullDetails);
  68244. }
  68245. }
  68246. // Geometries
  68247. var geometries = parsedData.geometries;
  68248. if (geometries !== undefined && geometries !== null) {
  68249. var addedGeometry = new Array();
  68250. // Boxes
  68251. var boxes = geometries.boxes;
  68252. if (boxes !== undefined && boxes !== null) {
  68253. for (index = 0, cache = boxes.length; index < cache; index++) {
  68254. var parsedBox = boxes[index];
  68255. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68256. }
  68257. }
  68258. // Spheres
  68259. var spheres = geometries.spheres;
  68260. if (spheres !== undefined && spheres !== null) {
  68261. for (index = 0, cache = spheres.length; index < cache; index++) {
  68262. var parsedSphere = spheres[index];
  68263. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68264. }
  68265. }
  68266. // Cylinders
  68267. var cylinders = geometries.cylinders;
  68268. if (cylinders !== undefined && cylinders !== null) {
  68269. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68270. var parsedCylinder = cylinders[index];
  68271. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68272. }
  68273. }
  68274. // Toruses
  68275. var toruses = geometries.toruses;
  68276. if (toruses !== undefined && toruses !== null) {
  68277. for (index = 0, cache = toruses.length; index < cache; index++) {
  68278. var parsedTorus = toruses[index];
  68279. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68280. }
  68281. }
  68282. // Grounds
  68283. var grounds = geometries.grounds;
  68284. if (grounds !== undefined && grounds !== null) {
  68285. for (index = 0, cache = grounds.length; index < cache; index++) {
  68286. var parsedGround = grounds[index];
  68287. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68288. }
  68289. }
  68290. // Planes
  68291. var planes = geometries.planes;
  68292. if (planes !== undefined && planes !== null) {
  68293. for (index = 0, cache = planes.length; index < cache; index++) {
  68294. var parsedPlane = planes[index];
  68295. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68296. }
  68297. }
  68298. // TorusKnots
  68299. var torusKnots = geometries.torusKnots;
  68300. if (torusKnots !== undefined && torusKnots !== null) {
  68301. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68302. var parsedTorusKnot = torusKnots[index];
  68303. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68304. }
  68305. }
  68306. // VertexData
  68307. var vertexData = geometries.vertexData;
  68308. if (vertexData !== undefined && vertexData !== null) {
  68309. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68310. var parsedVertexData = vertexData[index];
  68311. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68312. }
  68313. }
  68314. addedGeometry.forEach(function (g) {
  68315. if (g) {
  68316. container.geometries.push(g);
  68317. }
  68318. });
  68319. }
  68320. // Transform nodes
  68321. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68322. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68323. var parsedTransformNode = parsedData.transformNodes[index];
  68324. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68325. container.transformNodes.push(node);
  68326. }
  68327. }
  68328. // Meshes
  68329. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68330. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68331. var parsedMesh = parsedData.meshes[index];
  68332. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68333. container.meshes.push(mesh);
  68334. log += (index === 0 ? "\n\tMeshes:" : "");
  68335. log += "\n\t\t" + mesh.toString(fullDetails);
  68336. }
  68337. }
  68338. // Cameras
  68339. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68340. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68341. var parsedCamera = parsedData.cameras[index];
  68342. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68343. container.cameras.push(camera);
  68344. log += (index === 0 ? "\n\tCameras:" : "");
  68345. log += "\n\t\t" + camera.toString(fullDetails);
  68346. }
  68347. }
  68348. // Browsing all the graph to connect the dots
  68349. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68350. var camera = scene.cameras[index];
  68351. if (camera._waitingParentId) {
  68352. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68353. camera._waitingParentId = null;
  68354. }
  68355. }
  68356. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68357. var light_1 = scene.lights[index];
  68358. if (light_1 && light_1._waitingParentId) {
  68359. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68360. light_1._waitingParentId = null;
  68361. }
  68362. }
  68363. // Sounds
  68364. // TODO: add sound
  68365. var loadedSounds = [];
  68366. var loadedSound;
  68367. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68368. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68369. var parsedSound = parsedData.sounds[index];
  68370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68371. if (!parsedSound.url)
  68372. parsedSound.url = parsedSound.name;
  68373. if (!loadedSounds[parsedSound.url]) {
  68374. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68375. loadedSounds[parsedSound.url] = loadedSound;
  68376. container.sounds.push(loadedSound);
  68377. }
  68378. else {
  68379. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68380. }
  68381. }
  68382. else {
  68383. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68384. }
  68385. }
  68386. }
  68387. loadedSounds = [];
  68388. // Connect parents & children and parse actions
  68389. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68390. var transformNode = scene.transformNodes[index];
  68391. if (transformNode._waitingParentId) {
  68392. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68393. transformNode._waitingParentId = null;
  68394. }
  68395. }
  68396. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68397. var mesh = scene.meshes[index];
  68398. if (mesh._waitingParentId) {
  68399. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68400. mesh._waitingParentId = null;
  68401. }
  68402. if (mesh._waitingActions) {
  68403. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68404. mesh._waitingActions = null;
  68405. }
  68406. }
  68407. // freeze world matrix application
  68408. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68409. var currentMesh = scene.meshes[index];
  68410. if (currentMesh._waitingFreezeWorldMatrix) {
  68411. currentMesh.freezeWorldMatrix();
  68412. currentMesh._waitingFreezeWorldMatrix = null;
  68413. }
  68414. else {
  68415. currentMesh.computeWorldMatrix(true);
  68416. }
  68417. }
  68418. // Particles Systems
  68419. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68420. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68421. var parsedParticleSystem = parsedData.particleSystems[index];
  68422. if (parsedParticleSystem.activeParticleCount) {
  68423. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68424. container.particleSystems.push(ps);
  68425. }
  68426. else {
  68427. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68428. container.particleSystems.push(ps);
  68429. }
  68430. }
  68431. }
  68432. // Lens flares
  68433. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68434. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68435. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68436. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68437. container.lensFlareSystems.push(lf);
  68438. }
  68439. }
  68440. // Shadows
  68441. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68442. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68443. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68444. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68445. container.shadowGenerators.push(sg);
  68446. }
  68447. }
  68448. // Lights exclusions / inclusions
  68449. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68450. var light_2 = scene.lights[index];
  68451. // Excluded check
  68452. if (light_2._excludedMeshesIds.length > 0) {
  68453. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68454. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68455. if (excludedMesh) {
  68456. light_2.excludedMeshes.push(excludedMesh);
  68457. }
  68458. }
  68459. light_2._excludedMeshesIds = [];
  68460. }
  68461. // Included check
  68462. if (light_2._includedOnlyMeshesIds.length > 0) {
  68463. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68464. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68465. if (includedOnlyMesh) {
  68466. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68467. }
  68468. }
  68469. light_2._includedOnlyMeshesIds = [];
  68470. }
  68471. }
  68472. // Effect layers
  68473. if (parsedData.effectLayers) {
  68474. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68475. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68476. container.effectLayers.push(effectLayer);
  68477. }
  68478. }
  68479. // Actions (scene)
  68480. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68481. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68482. }
  68483. if (!addToScene) {
  68484. container.removeAllFromScene();
  68485. }
  68486. }
  68487. catch (err) {
  68488. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68489. if (onError) {
  68490. onError(msg, err);
  68491. }
  68492. else {
  68493. BABYLON.Tools.Log(msg);
  68494. throw err;
  68495. }
  68496. }
  68497. finally {
  68498. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68499. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68500. }
  68501. }
  68502. return container;
  68503. };
  68504. BABYLON.SceneLoader.RegisterPlugin({
  68505. name: "babylon.js",
  68506. extensions: ".babylon",
  68507. canDirectLoad: function (data) {
  68508. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68509. return true;
  68510. }
  68511. return false;
  68512. },
  68513. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68514. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68515. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68516. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68517. // and avoid problems with multiple concurrent .babylon loads.
  68518. var log = "importMesh has failed JSON parse";
  68519. try {
  68520. var parsedData = JSON.parse(data);
  68521. log = "";
  68522. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68523. if (!meshesNames) {
  68524. meshesNames = null;
  68525. }
  68526. else if (!Array.isArray(meshesNames)) {
  68527. meshesNames = [meshesNames];
  68528. }
  68529. var hierarchyIds = new Array();
  68530. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68531. var loadedSkeletonsIds = [];
  68532. var loadedMaterialsIds = [];
  68533. var index;
  68534. var cache;
  68535. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68536. var parsedMesh = parsedData.meshes[index];
  68537. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68538. if (meshesNames !== null) {
  68539. // Remove found mesh name from list.
  68540. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68541. }
  68542. //Geometry?
  68543. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68544. //does the file contain geometries?
  68545. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68546. //find the correct geometry and add it to the scene
  68547. var found = false;
  68548. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68549. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68550. return;
  68551. }
  68552. else {
  68553. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68554. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68555. switch (geometryType) {
  68556. case "boxes":
  68557. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68558. break;
  68559. case "spheres":
  68560. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68561. break;
  68562. case "cylinders":
  68563. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68564. break;
  68565. case "toruses":
  68566. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68567. break;
  68568. case "grounds":
  68569. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68570. break;
  68571. case "planes":
  68572. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68573. break;
  68574. case "torusKnots":
  68575. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68576. break;
  68577. case "vertexData":
  68578. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68579. break;
  68580. }
  68581. found = true;
  68582. }
  68583. });
  68584. }
  68585. });
  68586. if (found === false) {
  68587. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68588. }
  68589. }
  68590. }
  68591. // Material ?
  68592. if (parsedMesh.materialId) {
  68593. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68594. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68595. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68596. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68597. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68598. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68599. var subMatId = parsedMultiMaterial.materials[matIndex];
  68600. loadedMaterialsIds.push(subMatId);
  68601. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68602. if (mat) {
  68603. log += "\n\tMaterial " + mat.toString(fullDetails);
  68604. }
  68605. }
  68606. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68607. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68608. if (mmat) {
  68609. materialFound = true;
  68610. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68611. }
  68612. break;
  68613. }
  68614. }
  68615. }
  68616. if (materialFound === false) {
  68617. loadedMaterialsIds.push(parsedMesh.materialId);
  68618. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68619. if (!mat) {
  68620. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68621. }
  68622. else {
  68623. log += "\n\tMaterial " + mat.toString(fullDetails);
  68624. }
  68625. }
  68626. }
  68627. // Skeleton ?
  68628. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68629. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68630. if (skeletonAlreadyLoaded === false) {
  68631. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68632. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68633. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68634. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68635. skeletons.push(skeleton);
  68636. loadedSkeletonsIds.push(parsedSkeleton.id);
  68637. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68638. }
  68639. }
  68640. }
  68641. }
  68642. // Morph targets ?
  68643. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68644. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68645. var managerData = _a[_i];
  68646. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68647. }
  68648. }
  68649. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68650. meshes.push(mesh);
  68651. log += "\n\tMesh " + mesh.toString(fullDetails);
  68652. }
  68653. }
  68654. // Connecting parents
  68655. var currentMesh;
  68656. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68657. currentMesh = scene.meshes[index];
  68658. if (currentMesh._waitingParentId) {
  68659. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68660. currentMesh._waitingParentId = null;
  68661. }
  68662. }
  68663. // freeze and compute world matrix application
  68664. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68665. currentMesh = scene.meshes[index];
  68666. if (currentMesh._waitingFreezeWorldMatrix) {
  68667. currentMesh.freezeWorldMatrix();
  68668. currentMesh._waitingFreezeWorldMatrix = null;
  68669. }
  68670. else {
  68671. currentMesh.computeWorldMatrix(true);
  68672. }
  68673. }
  68674. }
  68675. // Particles
  68676. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68677. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68678. var parsedParticleSystem = parsedData.particleSystems[index];
  68679. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68680. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68681. }
  68682. }
  68683. }
  68684. return true;
  68685. }
  68686. catch (err) {
  68687. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68688. if (onError) {
  68689. onError(msg, err);
  68690. }
  68691. else {
  68692. BABYLON.Tools.Log(msg);
  68693. throw err;
  68694. }
  68695. }
  68696. finally {
  68697. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68698. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68699. }
  68700. }
  68701. return false;
  68702. },
  68703. load: function (scene, data, rootUrl, onError) {
  68704. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68705. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68706. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68707. // and avoid problems with multiple concurrent .babylon loads.
  68708. var log = "importScene has failed JSON parse";
  68709. try {
  68710. var parsedData = JSON.parse(data);
  68711. log = "";
  68712. // Scene
  68713. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68714. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68715. }
  68716. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68717. scene.autoClear = parsedData.autoClear;
  68718. }
  68719. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68720. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68721. }
  68722. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68723. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68724. }
  68725. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68726. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68727. }
  68728. // Fog
  68729. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68730. scene.fogMode = parsedData.fogMode;
  68731. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68732. scene.fogStart = parsedData.fogStart;
  68733. scene.fogEnd = parsedData.fogEnd;
  68734. scene.fogDensity = parsedData.fogDensity;
  68735. log += "\tFog mode for scene: ";
  68736. switch (scene.fogMode) {
  68737. // getters not compiling, so using hardcoded
  68738. case 1:
  68739. log += "exp\n";
  68740. break;
  68741. case 2:
  68742. log += "exp2\n";
  68743. break;
  68744. case 3:
  68745. log += "linear\n";
  68746. break;
  68747. }
  68748. }
  68749. //Physics
  68750. if (parsedData.physicsEnabled) {
  68751. var physicsPlugin;
  68752. if (parsedData.physicsEngine === "cannon") {
  68753. physicsPlugin = new BABYLON.CannonJSPlugin();
  68754. }
  68755. else if (parsedData.physicsEngine === "oimo") {
  68756. physicsPlugin = new BABYLON.OimoJSPlugin();
  68757. }
  68758. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68759. //else - default engine, which is currently oimo
  68760. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68761. scene.enablePhysics(physicsGravity, physicsPlugin);
  68762. }
  68763. // Metadata
  68764. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68765. scene.metadata = parsedData.metadata;
  68766. }
  68767. //collisions, if defined. otherwise, default is true
  68768. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68769. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68770. }
  68771. scene.workerCollisions = !!parsedData.workerCollisions;
  68772. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68773. if (!container) {
  68774. return false;
  68775. }
  68776. if (parsedData.autoAnimate) {
  68777. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68778. }
  68779. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68780. scene.setActiveCameraByID(parsedData.activeCameraID);
  68781. }
  68782. // Environment texture
  68783. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68784. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68785. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68786. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68787. if (parsedData.environmentTextureRotationY) {
  68788. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68789. }
  68790. scene.environmentTexture = hdrTexture;
  68791. }
  68792. else {
  68793. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68794. if (parsedData.environmentTextureRotationY) {
  68795. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68796. }
  68797. scene.environmentTexture = cubeTexture;
  68798. }
  68799. if (parsedData.createDefaultSkybox === true) {
  68800. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68801. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68802. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68803. }
  68804. }
  68805. // Finish
  68806. return true;
  68807. }
  68808. catch (err) {
  68809. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68810. if (onError) {
  68811. onError(msg, err);
  68812. }
  68813. else {
  68814. BABYLON.Tools.Log(msg);
  68815. throw err;
  68816. }
  68817. }
  68818. finally {
  68819. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68820. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68821. }
  68822. }
  68823. return false;
  68824. },
  68825. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68826. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68827. return container;
  68828. }
  68829. });
  68830. })(BABYLON || (BABYLON = {}));
  68831. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68832. var BABYLON;
  68833. (function (BABYLON) {
  68834. var FilesInput = /** @class */ (function () {
  68835. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68836. this.onProcessFileCallback = function () { return true; };
  68837. this._engine = engine;
  68838. this._currentScene = scene;
  68839. this._sceneLoadedCallback = sceneLoadedCallback;
  68840. this._progressCallback = progressCallback;
  68841. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68842. this._textureLoadingCallback = textureLoadingCallback;
  68843. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68844. this._onReloadCallback = onReloadCallback;
  68845. this._errorCallback = errorCallback;
  68846. }
  68847. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68848. var _this = this;
  68849. if (elementToMonitor) {
  68850. this._elementToMonitor = elementToMonitor;
  68851. this._dragEnterHandler = function (e) { _this.drag(e); };
  68852. this._dragOverHandler = function (e) { _this.drag(e); };
  68853. this._dropHandler = function (e) { _this.drop(e); };
  68854. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68855. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68856. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68857. }
  68858. };
  68859. FilesInput.prototype.dispose = function () {
  68860. if (!this._elementToMonitor) {
  68861. return;
  68862. }
  68863. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68864. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68865. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68866. };
  68867. FilesInput.prototype.renderFunction = function () {
  68868. if (this._additionalRenderLoopLogicCallback) {
  68869. this._additionalRenderLoopLogicCallback();
  68870. }
  68871. if (this._currentScene) {
  68872. if (this._textureLoadingCallback) {
  68873. var remaining = this._currentScene.getWaitingItemsCount();
  68874. if (remaining > 0) {
  68875. this._textureLoadingCallback(remaining);
  68876. }
  68877. }
  68878. this._currentScene.render();
  68879. }
  68880. };
  68881. FilesInput.prototype.drag = function (e) {
  68882. e.stopPropagation();
  68883. e.preventDefault();
  68884. };
  68885. FilesInput.prototype.drop = function (eventDrop) {
  68886. eventDrop.stopPropagation();
  68887. eventDrop.preventDefault();
  68888. this.loadFiles(eventDrop);
  68889. };
  68890. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68891. var _this = this;
  68892. var reader = folder.createReader();
  68893. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68894. reader.readEntries(function (entries) {
  68895. remaining.count += entries.length;
  68896. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68897. var entry = entries_1[_i];
  68898. if (entry.isFile) {
  68899. entry.file(function (file) {
  68900. file.correctName = relativePath + file.name;
  68901. files.push(file);
  68902. if (--remaining.count === 0) {
  68903. callback();
  68904. }
  68905. });
  68906. }
  68907. else if (entry.isDirectory) {
  68908. _this._traverseFolder(entry, files, remaining, callback);
  68909. }
  68910. }
  68911. if (--remaining.count) {
  68912. callback();
  68913. }
  68914. });
  68915. };
  68916. FilesInput.prototype._processFiles = function (files) {
  68917. for (var i = 0; i < files.length; i++) {
  68918. var name = files[i].correctName.toLowerCase();
  68919. var extension = name.split('.').pop();
  68920. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68921. continue;
  68922. }
  68923. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68924. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68925. this._sceneFileToLoad = files[i];
  68926. }
  68927. else {
  68928. FilesInput.FilesToLoad[name] = files[i];
  68929. }
  68930. }
  68931. };
  68932. FilesInput.prototype.loadFiles = function (event) {
  68933. var _this = this;
  68934. if (this._startingProcessingFilesCallback)
  68935. this._startingProcessingFilesCallback();
  68936. // Handling data transfer via drag'n'drop
  68937. if (event && event.dataTransfer && event.dataTransfer.files) {
  68938. this._filesToLoad = event.dataTransfer.files;
  68939. }
  68940. // Handling files from input files
  68941. if (event && event.target && event.target.files) {
  68942. this._filesToLoad = event.target.files;
  68943. }
  68944. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68945. var files_1 = new Array();
  68946. var folders = [];
  68947. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68948. for (var i = 0; i < this._filesToLoad.length; i++) {
  68949. var fileToLoad = this._filesToLoad[i];
  68950. var name_1 = fileToLoad.name.toLowerCase();
  68951. var entry = void 0;
  68952. fileToLoad.correctName = name_1;
  68953. if (items) {
  68954. var item = items[i];
  68955. if (item.getAsEntry) {
  68956. entry = item.getAsEntry();
  68957. }
  68958. else if (item.webkitGetAsEntry) {
  68959. entry = item.webkitGetAsEntry();
  68960. }
  68961. }
  68962. if (!entry) {
  68963. files_1.push(fileToLoad);
  68964. }
  68965. else {
  68966. if (entry.isDirectory) {
  68967. folders.push(entry);
  68968. }
  68969. else {
  68970. files_1.push(fileToLoad);
  68971. }
  68972. }
  68973. }
  68974. if (folders.length === 0) {
  68975. this._processFiles(files_1);
  68976. this._processReload();
  68977. }
  68978. else {
  68979. var remaining = { count: folders.length };
  68980. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68981. var folder = folders_1[_i];
  68982. this._traverseFolder(folder, files_1, remaining, function () {
  68983. _this._processFiles(files_1);
  68984. if (remaining.count === 0) {
  68985. _this._processReload();
  68986. }
  68987. });
  68988. }
  68989. }
  68990. }
  68991. };
  68992. FilesInput.prototype._processReload = function () {
  68993. if (this._onReloadCallback) {
  68994. this._onReloadCallback(this._sceneFileToLoad);
  68995. }
  68996. else {
  68997. this.reload();
  68998. }
  68999. };
  69000. FilesInput.prototype.reload = function () {
  69001. var _this = this;
  69002. // If a scene file has been provided
  69003. if (this._sceneFileToLoad) {
  69004. if (this._currentScene) {
  69005. if (BABYLON.Tools.errorsCount > 0) {
  69006. BABYLON.Tools.ClearLogCache();
  69007. }
  69008. this._engine.stopRenderLoop();
  69009. }
  69010. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69011. if (_this._progressCallback) {
  69012. _this._progressCallback(progress);
  69013. }
  69014. }).then(function (scene) {
  69015. if (_this._currentScene) {
  69016. _this._currentScene.dispose();
  69017. }
  69018. _this._currentScene = scene;
  69019. if (_this._sceneLoadedCallback) {
  69020. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69021. }
  69022. // Wait for textures and shaders to be ready
  69023. _this._currentScene.executeWhenReady(function () {
  69024. _this._engine.runRenderLoop(function () {
  69025. _this.renderFunction();
  69026. });
  69027. });
  69028. }).catch(function (error) {
  69029. if (_this._errorCallback) {
  69030. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69031. }
  69032. });
  69033. }
  69034. else {
  69035. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69036. }
  69037. };
  69038. FilesInput.FilesToLoad = {};
  69039. return FilesInput;
  69040. }());
  69041. BABYLON.FilesInput = FilesInput;
  69042. })(BABYLON || (BABYLON = {}));
  69043. //# sourceMappingURL=babylon.filesInput.js.map
  69044. var BABYLON;
  69045. (function (BABYLON) {
  69046. /**
  69047. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69048. * The underlying implementation relies on an associative array to ensure the best performances.
  69049. * The value can be anything including 'null' but except 'undefined'
  69050. */
  69051. var StringDictionary = /** @class */ (function () {
  69052. function StringDictionary() {
  69053. this._count = 0;
  69054. this._data = {};
  69055. }
  69056. /**
  69057. * This will clear this dictionary and copy the content from the 'source' one.
  69058. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69059. * @param source the dictionary to take the content from and copy to this dictionary
  69060. */
  69061. StringDictionary.prototype.copyFrom = function (source) {
  69062. var _this = this;
  69063. this.clear();
  69064. source.forEach(function (t, v) { return _this.add(t, v); });
  69065. };
  69066. /**
  69067. * Get a value based from its key
  69068. * @param key the given key to get the matching value from
  69069. * @return the value if found, otherwise undefined is returned
  69070. */
  69071. StringDictionary.prototype.get = function (key) {
  69072. var val = this._data[key];
  69073. if (val !== undefined) {
  69074. return val;
  69075. }
  69076. return undefined;
  69077. };
  69078. /**
  69079. * Get a value from its key or add it if it doesn't exist.
  69080. * This method will ensure you that a given key/data will be present in the dictionary.
  69081. * @param key the given key to get the matching value from
  69082. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69083. * The factory will only be invoked if there's no data for the given key.
  69084. * @return the value corresponding to the key.
  69085. */
  69086. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69087. var val = this.get(key);
  69088. if (val !== undefined) {
  69089. return val;
  69090. }
  69091. val = factory(key);
  69092. if (val) {
  69093. this.add(key, val);
  69094. }
  69095. return val;
  69096. };
  69097. /**
  69098. * Get a value from its key if present in the dictionary otherwise add it
  69099. * @param key the key to get the value from
  69100. * @param val if there's no such key/value pair in the dictionary add it with this value
  69101. * @return the value corresponding to the key
  69102. */
  69103. StringDictionary.prototype.getOrAdd = function (key, val) {
  69104. var curVal = this.get(key);
  69105. if (curVal !== undefined) {
  69106. return curVal;
  69107. }
  69108. this.add(key, val);
  69109. return val;
  69110. };
  69111. /**
  69112. * Check if there's a given key in the dictionary
  69113. * @param key the key to check for
  69114. * @return true if the key is present, false otherwise
  69115. */
  69116. StringDictionary.prototype.contains = function (key) {
  69117. return this._data[key] !== undefined;
  69118. };
  69119. /**
  69120. * Add a new key and its corresponding value
  69121. * @param key the key to add
  69122. * @param value the value corresponding to the key
  69123. * @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
  69124. */
  69125. StringDictionary.prototype.add = function (key, value) {
  69126. if (this._data[key] !== undefined) {
  69127. return false;
  69128. }
  69129. this._data[key] = value;
  69130. ++this._count;
  69131. return true;
  69132. };
  69133. StringDictionary.prototype.set = function (key, value) {
  69134. if (this._data[key] === undefined) {
  69135. return false;
  69136. }
  69137. this._data[key] = value;
  69138. return true;
  69139. };
  69140. /**
  69141. * Get the element of the given key and remove it from the dictionary
  69142. * @param key
  69143. */
  69144. StringDictionary.prototype.getAndRemove = function (key) {
  69145. var val = this.get(key);
  69146. if (val !== undefined) {
  69147. delete this._data[key];
  69148. --this._count;
  69149. return val;
  69150. }
  69151. return null;
  69152. };
  69153. /**
  69154. * Remove a key/value from the dictionary.
  69155. * @param key the key to remove
  69156. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69157. */
  69158. StringDictionary.prototype.remove = function (key) {
  69159. if (this.contains(key)) {
  69160. delete this._data[key];
  69161. --this._count;
  69162. return true;
  69163. }
  69164. return false;
  69165. };
  69166. /**
  69167. * Clear the whole content of the dictionary
  69168. */
  69169. StringDictionary.prototype.clear = function () {
  69170. this._data = {};
  69171. this._count = 0;
  69172. };
  69173. Object.defineProperty(StringDictionary.prototype, "count", {
  69174. get: function () {
  69175. return this._count;
  69176. },
  69177. enumerable: true,
  69178. configurable: true
  69179. });
  69180. /**
  69181. * Execute a callback on each key/val of the dictionary.
  69182. * Note that you can remove any element in this dictionary in the callback implementation
  69183. * @param callback the callback to execute on a given key/value pair
  69184. */
  69185. StringDictionary.prototype.forEach = function (callback) {
  69186. for (var cur in this._data) {
  69187. var val = this._data[cur];
  69188. callback(cur, val);
  69189. }
  69190. };
  69191. /**
  69192. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69193. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69194. * Note that you can remove any element in this dictionary in the callback implementation
  69195. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69196. */
  69197. StringDictionary.prototype.first = function (callback) {
  69198. for (var cur in this._data) {
  69199. var val = this._data[cur];
  69200. var res = callback(cur, val);
  69201. if (res) {
  69202. return res;
  69203. }
  69204. }
  69205. return null;
  69206. };
  69207. return StringDictionary;
  69208. }());
  69209. BABYLON.StringDictionary = StringDictionary;
  69210. })(BABYLON || (BABYLON = {}));
  69211. //# sourceMappingURL=babylon.stringDictionary.js.map
  69212. var BABYLON;
  69213. (function (BABYLON) {
  69214. var Tags = /** @class */ (function () {
  69215. function Tags() {
  69216. }
  69217. Tags.EnableFor = function (obj) {
  69218. obj._tags = obj._tags || {};
  69219. obj.hasTags = function () {
  69220. return Tags.HasTags(obj);
  69221. };
  69222. obj.addTags = function (tagsString) {
  69223. return Tags.AddTagsTo(obj, tagsString);
  69224. };
  69225. obj.removeTags = function (tagsString) {
  69226. return Tags.RemoveTagsFrom(obj, tagsString);
  69227. };
  69228. obj.matchesTagsQuery = function (tagsQuery) {
  69229. return Tags.MatchesQuery(obj, tagsQuery);
  69230. };
  69231. };
  69232. Tags.DisableFor = function (obj) {
  69233. delete obj._tags;
  69234. delete obj.hasTags;
  69235. delete obj.addTags;
  69236. delete obj.removeTags;
  69237. delete obj.matchesTagsQuery;
  69238. };
  69239. Tags.HasTags = function (obj) {
  69240. if (!obj._tags) {
  69241. return false;
  69242. }
  69243. return !BABYLON.Tools.IsEmpty(obj._tags);
  69244. };
  69245. Tags.GetTags = function (obj, asString) {
  69246. if (asString === void 0) { asString = true; }
  69247. if (!obj._tags) {
  69248. return null;
  69249. }
  69250. if (asString) {
  69251. var tagsArray = [];
  69252. for (var tag in obj._tags) {
  69253. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69254. tagsArray.push(tag);
  69255. }
  69256. }
  69257. return tagsArray.join(" ");
  69258. }
  69259. else {
  69260. return obj._tags;
  69261. }
  69262. };
  69263. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69264. // a tag cannot start with '||', '&&', and '!'
  69265. // it cannot contain whitespaces
  69266. Tags.AddTagsTo = function (obj, tagsString) {
  69267. if (!tagsString) {
  69268. return;
  69269. }
  69270. if (typeof tagsString !== "string") {
  69271. return;
  69272. }
  69273. var tags = tagsString.split(" ");
  69274. tags.forEach(function (tag, index, array) {
  69275. Tags._AddTagTo(obj, tag);
  69276. });
  69277. };
  69278. Tags._AddTagTo = function (obj, tag) {
  69279. tag = tag.trim();
  69280. if (tag === "" || tag === "true" || tag === "false") {
  69281. return;
  69282. }
  69283. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69284. return;
  69285. }
  69286. Tags.EnableFor(obj);
  69287. obj._tags[tag] = true;
  69288. };
  69289. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69290. if (!Tags.HasTags(obj)) {
  69291. return;
  69292. }
  69293. var tags = tagsString.split(" ");
  69294. for (var t in tags) {
  69295. Tags._RemoveTagFrom(obj, tags[t]);
  69296. }
  69297. };
  69298. Tags._RemoveTagFrom = function (obj, tag) {
  69299. delete obj._tags[tag];
  69300. };
  69301. Tags.MatchesQuery = function (obj, tagsQuery) {
  69302. if (tagsQuery === undefined) {
  69303. return true;
  69304. }
  69305. if (tagsQuery === "") {
  69306. return Tags.HasTags(obj);
  69307. }
  69308. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69309. };
  69310. return Tags;
  69311. }());
  69312. BABYLON.Tags = Tags;
  69313. })(BABYLON || (BABYLON = {}));
  69314. //# sourceMappingURL=babylon.tags.js.map
  69315. var BABYLON;
  69316. (function (BABYLON) {
  69317. /**
  69318. * Class used to evalaute queries containing `and` and `or` operators
  69319. */
  69320. var AndOrNotEvaluator = /** @class */ (function () {
  69321. function AndOrNotEvaluator() {
  69322. }
  69323. /**
  69324. * Evaluate a query
  69325. * @param query defines the query to evaluate
  69326. * @param evaluateCallback defines the callback used to filter result
  69327. * @returns true if the query matches
  69328. */
  69329. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69330. if (!query.match(/\([^\(\)]*\)/g)) {
  69331. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69332. }
  69333. else {
  69334. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69335. // remove parenthesis
  69336. r = r.slice(1, r.length - 1);
  69337. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69338. });
  69339. }
  69340. if (query === "true") {
  69341. return true;
  69342. }
  69343. if (query === "false") {
  69344. return false;
  69345. }
  69346. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69347. };
  69348. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69349. evaluateCallback = evaluateCallback || (function (r) {
  69350. return r === "true" ? true : false;
  69351. });
  69352. var result;
  69353. var or = parenthesisContent.split("||");
  69354. for (var i in or) {
  69355. if (or.hasOwnProperty(i)) {
  69356. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69357. var and = ori.split("&&");
  69358. if (and.length > 1) {
  69359. for (var j = 0; j < and.length; ++j) {
  69360. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69361. if (andj !== "true" && andj !== "false") {
  69362. if (andj[0] === "!") {
  69363. result = !evaluateCallback(andj.substring(1));
  69364. }
  69365. else {
  69366. result = evaluateCallback(andj);
  69367. }
  69368. }
  69369. else {
  69370. result = andj === "true" ? true : false;
  69371. }
  69372. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69373. ori = "false";
  69374. break;
  69375. }
  69376. }
  69377. }
  69378. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69379. result = true;
  69380. break;
  69381. }
  69382. // result equals false (or undefined)
  69383. if (ori !== "true" && ori !== "false") {
  69384. if (ori[0] === "!") {
  69385. result = !evaluateCallback(ori.substring(1));
  69386. }
  69387. else {
  69388. result = evaluateCallback(ori);
  69389. }
  69390. }
  69391. else {
  69392. result = ori === "true" ? true : false;
  69393. }
  69394. }
  69395. }
  69396. // the whole parenthesis scope is replaced by 'true' or 'false'
  69397. return result ? "true" : "false";
  69398. };
  69399. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69400. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69401. // remove whitespaces
  69402. r = r.replace(/[\s]/g, function () { return ""; });
  69403. return r.length % 2 ? "!" : "";
  69404. });
  69405. booleanString = booleanString.trim();
  69406. if (booleanString === "!true") {
  69407. booleanString = "false";
  69408. }
  69409. else if (booleanString === "!false") {
  69410. booleanString = "true";
  69411. }
  69412. return booleanString;
  69413. };
  69414. return AndOrNotEvaluator;
  69415. }());
  69416. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69417. })(BABYLON || (BABYLON = {}));
  69418. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69419. var BABYLON;
  69420. (function (BABYLON) {
  69421. /**
  69422. * Class used to enable access to IndexedDB
  69423. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69424. */
  69425. var Database = /** @class */ (function () {
  69426. /**
  69427. * Creates a new Database
  69428. * @param urlToScene defines the url to load the scene
  69429. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69430. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69431. */
  69432. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69433. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69434. var _this = this;
  69435. // Handling various flavors of prefixed version of IndexedDB
  69436. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69437. this.callbackManifestChecked = callbackManifestChecked;
  69438. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69439. this.db = null;
  69440. this._enableSceneOffline = false;
  69441. this._enableTexturesOffline = false;
  69442. this.manifestVersionFound = 0;
  69443. this.mustUpdateRessources = false;
  69444. this.hasReachedQuota = false;
  69445. if (!Database.IDBStorageEnabled) {
  69446. this.callbackManifestChecked(true);
  69447. }
  69448. else {
  69449. if (disableManifestCheck) {
  69450. this._enableSceneOffline = true;
  69451. this._enableTexturesOffline = true;
  69452. this.manifestVersionFound = 1;
  69453. BABYLON.Tools.SetImmediate(function () {
  69454. _this.callbackManifestChecked(true);
  69455. });
  69456. }
  69457. else {
  69458. this._checkManifestFile();
  69459. }
  69460. }
  69461. }
  69462. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69463. /**
  69464. * Gets a boolean indicating if scene must be saved in the database
  69465. */
  69466. get: function () {
  69467. return this._enableSceneOffline;
  69468. },
  69469. enumerable: true,
  69470. configurable: true
  69471. });
  69472. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69473. /**
  69474. * Gets a boolean indicating if textures must be saved in the database
  69475. */
  69476. get: function () {
  69477. return this._enableTexturesOffline;
  69478. },
  69479. enumerable: true,
  69480. configurable: true
  69481. });
  69482. Database.prototype._checkManifestFile = function () {
  69483. var _this = this;
  69484. var noManifestFile = function () {
  69485. _this._enableSceneOffline = false;
  69486. _this._enableTexturesOffline = false;
  69487. _this.callbackManifestChecked(false);
  69488. };
  69489. var timeStampUsed = false;
  69490. var manifestURL = this.currentSceneUrl + ".manifest";
  69491. var xhr = new XMLHttpRequest();
  69492. if (navigator.onLine) {
  69493. // Adding a timestamp to by-pass browsers' cache
  69494. timeStampUsed = true;
  69495. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69496. }
  69497. xhr.open("GET", manifestURL, true);
  69498. xhr.addEventListener("load", function () {
  69499. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69500. try {
  69501. var manifestFile = JSON.parse(xhr.response);
  69502. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69503. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69504. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69505. _this.manifestVersionFound = manifestFile.version;
  69506. }
  69507. if (_this.callbackManifestChecked) {
  69508. _this.callbackManifestChecked(true);
  69509. }
  69510. }
  69511. catch (ex) {
  69512. noManifestFile();
  69513. }
  69514. }
  69515. else {
  69516. noManifestFile();
  69517. }
  69518. }, false);
  69519. xhr.addEventListener("error", function (event) {
  69520. if (timeStampUsed) {
  69521. timeStampUsed = false;
  69522. // Let's retry without the timeStamp
  69523. // It could fail when coupled with HTML5 Offline API
  69524. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69525. xhr.open("GET", retryManifestURL, true);
  69526. xhr.send();
  69527. }
  69528. else {
  69529. noManifestFile();
  69530. }
  69531. }, false);
  69532. try {
  69533. xhr.send();
  69534. }
  69535. catch (ex) {
  69536. BABYLON.Tools.Error("Error on XHR send request.");
  69537. this.callbackManifestChecked(false);
  69538. }
  69539. };
  69540. /**
  69541. * Open the database and make it available
  69542. * @param successCallback defines the callback to call on success
  69543. * @param errorCallback defines the callback to call on error
  69544. */
  69545. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69546. var _this = this;
  69547. var handleError = function () {
  69548. _this.isSupported = false;
  69549. if (errorCallback)
  69550. errorCallback();
  69551. };
  69552. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69553. // Your browser doesn't support IndexedDB
  69554. this.isSupported = false;
  69555. if (errorCallback)
  69556. errorCallback();
  69557. }
  69558. else {
  69559. // If the DB hasn't been opened or created yet
  69560. if (!this.db) {
  69561. this.hasReachedQuota = false;
  69562. this.isSupported = true;
  69563. var request = this.idbFactory.open("babylonjs", 1);
  69564. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69565. request.onerror = function (event) {
  69566. handleError();
  69567. };
  69568. // executes when a version change transaction cannot complete due to other active transactions
  69569. request.onblocked = function (event) {
  69570. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69571. handleError();
  69572. };
  69573. // DB has been opened successfully
  69574. request.onsuccess = function (event) {
  69575. _this.db = request.result;
  69576. successCallback();
  69577. };
  69578. // Initialization of the DB. Creating Scenes & Textures stores
  69579. request.onupgradeneeded = function (event) {
  69580. _this.db = (event.target).result;
  69581. if (_this.db) {
  69582. try {
  69583. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69584. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69585. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69586. }
  69587. catch (ex) {
  69588. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69589. handleError();
  69590. }
  69591. }
  69592. };
  69593. }
  69594. // DB has already been created and opened
  69595. else {
  69596. if (successCallback)
  69597. successCallback();
  69598. }
  69599. }
  69600. };
  69601. /**
  69602. * Loads an image from the database
  69603. * @param url defines the url to load from
  69604. * @param image defines the target DOM image
  69605. */
  69606. Database.prototype.loadImageFromDB = function (url, image) {
  69607. var _this = this;
  69608. var completeURL = Database._ReturnFullUrlLocation(url);
  69609. var saveAndLoadImage = function () {
  69610. if (!_this.hasReachedQuota && _this.db !== null) {
  69611. // the texture is not yet in the DB, let's try to save it
  69612. _this._saveImageIntoDBAsync(completeURL, image);
  69613. }
  69614. // If the texture is not in the DB and we've reached the DB quota limit
  69615. // let's load it directly from the web
  69616. else {
  69617. image.src = url;
  69618. }
  69619. };
  69620. if (!this.mustUpdateRessources) {
  69621. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69622. }
  69623. // First time we're download the images or update requested in the manifest file by a version change
  69624. else {
  69625. saveAndLoadImage();
  69626. }
  69627. };
  69628. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69629. if (this.isSupported && this.db !== null) {
  69630. var texture;
  69631. var transaction = this.db.transaction(["textures"]);
  69632. transaction.onabort = function (event) {
  69633. image.src = url;
  69634. };
  69635. transaction.oncomplete = function (event) {
  69636. var blobTextureURL;
  69637. if (texture) {
  69638. var URL = window.URL || window.webkitURL;
  69639. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69640. image.onerror = function () {
  69641. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69642. image.src = url;
  69643. };
  69644. image.src = blobTextureURL;
  69645. }
  69646. else {
  69647. notInDBCallback();
  69648. }
  69649. };
  69650. var getRequest = transaction.objectStore("textures").get(url);
  69651. getRequest.onsuccess = function (event) {
  69652. texture = (event.target).result;
  69653. };
  69654. getRequest.onerror = function (event) {
  69655. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69656. image.src = url;
  69657. };
  69658. }
  69659. else {
  69660. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69661. image.src = url;
  69662. }
  69663. };
  69664. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69665. var _this = this;
  69666. if (this.isSupported) {
  69667. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69668. var generateBlobUrl = function () {
  69669. var blobTextureURL;
  69670. if (blob) {
  69671. var URL = window.URL || window.webkitURL;
  69672. try {
  69673. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69674. }
  69675. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69676. catch (ex) {
  69677. blobTextureURL = URL.createObjectURL(blob);
  69678. }
  69679. }
  69680. if (blobTextureURL) {
  69681. image.src = blobTextureURL;
  69682. }
  69683. };
  69684. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69685. var xhr = new XMLHttpRequest(), blob;
  69686. xhr.open("GET", url, true);
  69687. xhr.responseType = "blob";
  69688. xhr.addEventListener("load", function () {
  69689. if (xhr.status === 200 && _this.db) {
  69690. // Blob as response (XHR2)
  69691. blob = xhr.response;
  69692. var transaction = _this.db.transaction(["textures"], "readwrite");
  69693. // the transaction could abort because of a QuotaExceededError error
  69694. transaction.onabort = function (event) {
  69695. try {
  69696. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69697. var srcElement = (event.srcElement || event.target);
  69698. var error = srcElement.error;
  69699. if (error && error.name === "QuotaExceededError") {
  69700. _this.hasReachedQuota = true;
  69701. }
  69702. }
  69703. catch (ex) { }
  69704. generateBlobUrl();
  69705. };
  69706. transaction.oncomplete = function (event) {
  69707. generateBlobUrl();
  69708. };
  69709. var newTexture = { textureUrl: url, data: blob };
  69710. try {
  69711. // Put the blob into the dabase
  69712. var addRequest = transaction.objectStore("textures").put(newTexture);
  69713. addRequest.onsuccess = function (event) {
  69714. };
  69715. addRequest.onerror = function (event) {
  69716. generateBlobUrl();
  69717. };
  69718. }
  69719. catch (ex) {
  69720. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69721. if (ex.code === 25) {
  69722. Database.IsUASupportingBlobStorage = false;
  69723. }
  69724. image.src = url;
  69725. }
  69726. }
  69727. else {
  69728. image.src = url;
  69729. }
  69730. }, false);
  69731. xhr.addEventListener("error", function (event) {
  69732. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69733. image.src = url;
  69734. }, false);
  69735. xhr.send();
  69736. }
  69737. else {
  69738. image.src = url;
  69739. }
  69740. }
  69741. else {
  69742. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69743. image.src = url;
  69744. }
  69745. };
  69746. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69747. var _this = this;
  69748. var updateVersion = function () {
  69749. // the version is not yet in the DB or we need to update it
  69750. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69751. };
  69752. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69753. };
  69754. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69755. var _this = this;
  69756. if (this.isSupported && this.db) {
  69757. var version;
  69758. try {
  69759. var transaction = this.db.transaction(["versions"]);
  69760. transaction.oncomplete = function (event) {
  69761. if (version) {
  69762. // If the version in the JSON file is different from the version in DB
  69763. if (_this.manifestVersionFound !== version.data) {
  69764. _this.mustUpdateRessources = true;
  69765. updateInDBCallback();
  69766. }
  69767. else {
  69768. callback(version.data);
  69769. }
  69770. }
  69771. // version was not found in DB
  69772. else {
  69773. _this.mustUpdateRessources = true;
  69774. updateInDBCallback();
  69775. }
  69776. };
  69777. transaction.onabort = function (event) {
  69778. callback(-1);
  69779. };
  69780. var getRequest = transaction.objectStore("versions").get(url);
  69781. getRequest.onsuccess = function (event) {
  69782. version = (event.target).result;
  69783. };
  69784. getRequest.onerror = function (event) {
  69785. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69786. callback(-1);
  69787. };
  69788. }
  69789. catch (ex) {
  69790. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69791. callback(-1);
  69792. }
  69793. }
  69794. else {
  69795. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69796. callback(-1);
  69797. }
  69798. };
  69799. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69800. var _this = this;
  69801. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69802. try {
  69803. // Open a transaction to the database
  69804. var transaction = this.db.transaction(["versions"], "readwrite");
  69805. // the transaction could abort because of a QuotaExceededError error
  69806. transaction.onabort = function (event) {
  69807. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69808. var error = event.srcElement['error'];
  69809. if (error && error.name === "QuotaExceededError") {
  69810. _this.hasReachedQuota = true;
  69811. }
  69812. }
  69813. catch (ex) { }
  69814. callback(-1);
  69815. };
  69816. transaction.oncomplete = function (event) {
  69817. callback(_this.manifestVersionFound);
  69818. };
  69819. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69820. // Put the scene into the database
  69821. var addRequest = transaction.objectStore("versions").put(newVersion);
  69822. addRequest.onsuccess = function (event) {
  69823. };
  69824. addRequest.onerror = function (event) {
  69825. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69826. };
  69827. }
  69828. catch (ex) {
  69829. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69830. callback(-1);
  69831. }
  69832. }
  69833. else {
  69834. callback(-1);
  69835. }
  69836. };
  69837. /**
  69838. * Loads a file from database
  69839. * @param url defines the URL to load from
  69840. * @param sceneLoaded defines a callback to call on success
  69841. * @param progressCallBack defines a callback to call when progress changed
  69842. * @param errorCallback defines a callback to call on error
  69843. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69844. */
  69845. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69846. var _this = this;
  69847. var completeUrl = Database._ReturnFullUrlLocation(url);
  69848. var saveAndLoadFile = function () {
  69849. // the scene is not yet in the DB, let's try to save it
  69850. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69851. };
  69852. this._checkVersionFromDB(completeUrl, function (version) {
  69853. if (version !== -1) {
  69854. if (!_this.mustUpdateRessources) {
  69855. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69856. }
  69857. else {
  69858. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69859. }
  69860. }
  69861. else {
  69862. if (errorCallback) {
  69863. errorCallback();
  69864. }
  69865. }
  69866. });
  69867. };
  69868. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69869. if (this.isSupported && this.db) {
  69870. var targetStore;
  69871. if (url.indexOf(".babylon") !== -1) {
  69872. targetStore = "scenes";
  69873. }
  69874. else {
  69875. targetStore = "textures";
  69876. }
  69877. var file;
  69878. var transaction = this.db.transaction([targetStore]);
  69879. transaction.oncomplete = function (event) {
  69880. if (file) {
  69881. callback(file.data);
  69882. }
  69883. // file was not found in DB
  69884. else {
  69885. notInDBCallback();
  69886. }
  69887. };
  69888. transaction.onabort = function (event) {
  69889. notInDBCallback();
  69890. };
  69891. var getRequest = transaction.objectStore(targetStore).get(url);
  69892. getRequest.onsuccess = function (event) {
  69893. file = (event.target).result;
  69894. };
  69895. getRequest.onerror = function (event) {
  69896. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69897. notInDBCallback();
  69898. };
  69899. }
  69900. else {
  69901. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69902. callback();
  69903. }
  69904. };
  69905. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69906. var _this = this;
  69907. if (this.isSupported) {
  69908. var targetStore;
  69909. if (url.indexOf(".babylon") !== -1) {
  69910. targetStore = "scenes";
  69911. }
  69912. else {
  69913. targetStore = "textures";
  69914. }
  69915. // Create XHR
  69916. var xhr = new XMLHttpRequest();
  69917. var fileData;
  69918. xhr.open("GET", url, true);
  69919. if (useArrayBuffer) {
  69920. xhr.responseType = "arraybuffer";
  69921. }
  69922. if (progressCallback) {
  69923. xhr.onprogress = progressCallback;
  69924. }
  69925. xhr.addEventListener("load", function () {
  69926. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69927. // Blob as response (XHR2)
  69928. //fileData = xhr.responseText;
  69929. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69930. if (!_this.hasReachedQuota && _this.db) {
  69931. // Open a transaction to the database
  69932. var transaction = _this.db.transaction([targetStore], "readwrite");
  69933. // the transaction could abort because of a QuotaExceededError error
  69934. transaction.onabort = function (event) {
  69935. try {
  69936. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69937. var error = event.srcElement['error'];
  69938. if (error && error.name === "QuotaExceededError") {
  69939. _this.hasReachedQuota = true;
  69940. }
  69941. }
  69942. catch (ex) { }
  69943. callback(fileData);
  69944. };
  69945. transaction.oncomplete = function (event) {
  69946. callback(fileData);
  69947. };
  69948. var newFile;
  69949. if (targetStore === "scenes") {
  69950. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69951. }
  69952. else {
  69953. newFile = { textureUrl: url, data: fileData };
  69954. }
  69955. try {
  69956. // Put the scene into the database
  69957. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69958. addRequest.onsuccess = function (event) {
  69959. };
  69960. addRequest.onerror = function (event) {
  69961. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69962. };
  69963. }
  69964. catch (ex) {
  69965. callback(fileData);
  69966. }
  69967. }
  69968. else {
  69969. callback(fileData);
  69970. }
  69971. }
  69972. else {
  69973. callback();
  69974. }
  69975. }, false);
  69976. xhr.addEventListener("error", function (event) {
  69977. BABYLON.Tools.Error("error on XHR request.");
  69978. callback();
  69979. }, false);
  69980. xhr.send();
  69981. }
  69982. else {
  69983. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69984. callback();
  69985. }
  69986. };
  69987. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69988. Database.IsUASupportingBlobStorage = true;
  69989. /** Gets a boolean indicating if Database storate is enabled */
  69990. Database.IDBStorageEnabled = true;
  69991. Database._ParseURL = function (url) {
  69992. var a = document.createElement('a');
  69993. a.href = url;
  69994. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69995. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69996. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69997. return absLocation;
  69998. };
  69999. Database._ReturnFullUrlLocation = function (url) {
  70000. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70001. return (Database._ParseURL(window.location.href) + url);
  70002. }
  70003. else {
  70004. return url;
  70005. }
  70006. };
  70007. return Database;
  70008. }());
  70009. BABYLON.Database = Database;
  70010. })(BABYLON || (BABYLON = {}));
  70011. //# sourceMappingURL=babylon.database.js.map
  70012. var BABYLON;
  70013. (function (BABYLON) {
  70014. var FresnelParameters = /** @class */ (function () {
  70015. function FresnelParameters() {
  70016. this._isEnabled = true;
  70017. this.leftColor = BABYLON.Color3.White();
  70018. this.rightColor = BABYLON.Color3.Black();
  70019. this.bias = 0;
  70020. this.power = 1;
  70021. }
  70022. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70023. get: function () {
  70024. return this._isEnabled;
  70025. },
  70026. set: function (value) {
  70027. if (this._isEnabled === value) {
  70028. return;
  70029. }
  70030. this._isEnabled = value;
  70031. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70032. },
  70033. enumerable: true,
  70034. configurable: true
  70035. });
  70036. FresnelParameters.prototype.clone = function () {
  70037. var newFresnelParameters = new FresnelParameters();
  70038. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70039. return newFresnelParameters;
  70040. };
  70041. FresnelParameters.prototype.serialize = function () {
  70042. var serializationObject = {};
  70043. serializationObject.isEnabled = this.isEnabled;
  70044. serializationObject.leftColor = this.leftColor.asArray();
  70045. serializationObject.rightColor = this.rightColor.asArray();
  70046. serializationObject.bias = this.bias;
  70047. serializationObject.power = this.power;
  70048. return serializationObject;
  70049. };
  70050. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70051. var fresnelParameters = new FresnelParameters();
  70052. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70053. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70054. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70055. fresnelParameters.bias = parsedFresnelParameters.bias;
  70056. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70057. return fresnelParameters;
  70058. };
  70059. return FresnelParameters;
  70060. }());
  70061. BABYLON.FresnelParameters = FresnelParameters;
  70062. })(BABYLON || (BABYLON = {}));
  70063. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70064. var BABYLON;
  70065. (function (BABYLON) {
  70066. var MultiMaterial = /** @class */ (function (_super) {
  70067. __extends(MultiMaterial, _super);
  70068. function MultiMaterial(name, scene) {
  70069. var _this = _super.call(this, name, scene, true) || this;
  70070. scene.multiMaterials.push(_this);
  70071. _this.subMaterials = new Array();
  70072. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70073. return _this;
  70074. }
  70075. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70076. get: function () {
  70077. return this._subMaterials;
  70078. },
  70079. set: function (value) {
  70080. this._subMaterials = value;
  70081. this._hookArray(value);
  70082. },
  70083. enumerable: true,
  70084. configurable: true
  70085. });
  70086. MultiMaterial.prototype._hookArray = function (array) {
  70087. var _this = this;
  70088. var oldPush = array.push;
  70089. array.push = function () {
  70090. var items = [];
  70091. for (var _i = 0; _i < arguments.length; _i++) {
  70092. items[_i] = arguments[_i];
  70093. }
  70094. var result = oldPush.apply(array, items);
  70095. _this._markAllSubMeshesAsTexturesDirty();
  70096. return result;
  70097. };
  70098. var oldSplice = array.splice;
  70099. array.splice = function (index, deleteCount) {
  70100. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70101. _this._markAllSubMeshesAsTexturesDirty();
  70102. return deleted;
  70103. };
  70104. };
  70105. // Properties
  70106. MultiMaterial.prototype.getSubMaterial = function (index) {
  70107. if (index < 0 || index >= this.subMaterials.length) {
  70108. return this.getScene().defaultMaterial;
  70109. }
  70110. return this.subMaterials[index];
  70111. };
  70112. MultiMaterial.prototype.getActiveTextures = function () {
  70113. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70114. if (subMaterial) {
  70115. return subMaterial.getActiveTextures();
  70116. }
  70117. else {
  70118. return [];
  70119. }
  70120. }));
  70121. var _a;
  70122. };
  70123. // Methods
  70124. MultiMaterial.prototype.getClassName = function () {
  70125. return "MultiMaterial";
  70126. };
  70127. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70128. for (var index = 0; index < this.subMaterials.length; index++) {
  70129. var subMaterial = this.subMaterials[index];
  70130. if (subMaterial) {
  70131. if (subMaterial.storeEffectOnSubMeshes) {
  70132. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70133. return false;
  70134. }
  70135. continue;
  70136. }
  70137. if (!subMaterial.isReady(mesh)) {
  70138. return false;
  70139. }
  70140. }
  70141. }
  70142. return true;
  70143. };
  70144. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70145. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70146. for (var index = 0; index < this.subMaterials.length; index++) {
  70147. var subMaterial = null;
  70148. var current = this.subMaterials[index];
  70149. if (cloneChildren && current) {
  70150. subMaterial = current.clone(name + "-" + current.name);
  70151. }
  70152. else {
  70153. subMaterial = this.subMaterials[index];
  70154. }
  70155. newMultiMaterial.subMaterials.push(subMaterial);
  70156. }
  70157. return newMultiMaterial;
  70158. };
  70159. MultiMaterial.prototype.serialize = function () {
  70160. var serializationObject = {};
  70161. serializationObject.name = this.name;
  70162. serializationObject.id = this.id;
  70163. if (BABYLON.Tags) {
  70164. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70165. }
  70166. serializationObject.materials = [];
  70167. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70168. var subMat = this.subMaterials[matIndex];
  70169. if (subMat) {
  70170. serializationObject.materials.push(subMat.id);
  70171. }
  70172. else {
  70173. serializationObject.materials.push(null);
  70174. }
  70175. }
  70176. return serializationObject;
  70177. };
  70178. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70179. var scene = this.getScene();
  70180. if (!scene) {
  70181. return;
  70182. }
  70183. var index = scene.multiMaterials.indexOf(this);
  70184. if (index >= 0) {
  70185. scene.multiMaterials.splice(index, 1);
  70186. }
  70187. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70188. };
  70189. return MultiMaterial;
  70190. }(BABYLON.Material));
  70191. BABYLON.MultiMaterial = MultiMaterial;
  70192. })(BABYLON || (BABYLON = {}));
  70193. //# sourceMappingURL=babylon.multiMaterial.js.map
  70194. var BABYLON;
  70195. (function (BABYLON) {
  70196. var FreeCameraTouchInput = /** @class */ (function () {
  70197. function FreeCameraTouchInput() {
  70198. this._offsetX = null;
  70199. this._offsetY = null;
  70200. this._pointerPressed = new Array();
  70201. this.touchAngularSensibility = 200000.0;
  70202. this.touchMoveSensibility = 250.0;
  70203. }
  70204. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70205. var _this = this;
  70206. var previousPosition = null;
  70207. if (this._pointerInput === undefined) {
  70208. this._onLostFocus = function (evt) {
  70209. _this._offsetX = null;
  70210. _this._offsetY = null;
  70211. };
  70212. this._pointerInput = function (p, s) {
  70213. var evt = p.event;
  70214. if (evt.pointerType === "mouse") {
  70215. return;
  70216. }
  70217. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70218. if (!noPreventDefault) {
  70219. evt.preventDefault();
  70220. }
  70221. _this._pointerPressed.push(evt.pointerId);
  70222. if (_this._pointerPressed.length !== 1) {
  70223. return;
  70224. }
  70225. previousPosition = {
  70226. x: evt.clientX,
  70227. y: evt.clientY
  70228. };
  70229. }
  70230. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70231. if (!noPreventDefault) {
  70232. evt.preventDefault();
  70233. }
  70234. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70235. if (index === -1) {
  70236. return;
  70237. }
  70238. _this._pointerPressed.splice(index, 1);
  70239. if (index != 0) {
  70240. return;
  70241. }
  70242. previousPosition = null;
  70243. _this._offsetX = null;
  70244. _this._offsetY = null;
  70245. }
  70246. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70247. if (!noPreventDefault) {
  70248. evt.preventDefault();
  70249. }
  70250. if (!previousPosition) {
  70251. return;
  70252. }
  70253. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70254. if (index != 0) {
  70255. return;
  70256. }
  70257. _this._offsetX = evt.clientX - previousPosition.x;
  70258. _this._offsetY = -(evt.clientY - previousPosition.y);
  70259. }
  70260. };
  70261. }
  70262. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70263. if (this._onLostFocus) {
  70264. element.addEventListener("blur", this._onLostFocus);
  70265. }
  70266. };
  70267. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70268. if (this._pointerInput && element) {
  70269. if (this._observer) {
  70270. this.camera.getScene().onPointerObservable.remove(this._observer);
  70271. this._observer = null;
  70272. }
  70273. if (this._onLostFocus) {
  70274. element.removeEventListener("blur", this._onLostFocus);
  70275. this._onLostFocus = null;
  70276. }
  70277. this._pointerPressed = [];
  70278. this._offsetX = null;
  70279. this._offsetY = null;
  70280. }
  70281. };
  70282. FreeCameraTouchInput.prototype.checkInputs = function () {
  70283. if (this._offsetX && this._offsetY) {
  70284. var camera = this.camera;
  70285. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70286. if (this._pointerPressed.length > 1) {
  70287. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70288. }
  70289. else {
  70290. var speed = camera._computeLocalCameraSpeed();
  70291. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70292. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70293. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70294. }
  70295. }
  70296. };
  70297. FreeCameraTouchInput.prototype.getClassName = function () {
  70298. return "FreeCameraTouchInput";
  70299. };
  70300. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70301. return "touch";
  70302. };
  70303. __decorate([
  70304. BABYLON.serialize()
  70305. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70306. __decorate([
  70307. BABYLON.serialize()
  70308. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70309. return FreeCameraTouchInput;
  70310. }());
  70311. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70312. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70313. })(BABYLON || (BABYLON = {}));
  70314. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70315. var BABYLON;
  70316. (function (BABYLON) {
  70317. // We're mainly based on the logic defined into the FreeCamera code
  70318. var TouchCamera = /** @class */ (function (_super) {
  70319. __extends(TouchCamera, _super);
  70320. //-- end properties for backward compatibility for inputs
  70321. function TouchCamera(name, position, scene) {
  70322. var _this = _super.call(this, name, position, scene) || this;
  70323. _this.inputs.addTouch();
  70324. _this._setupInputs();
  70325. return _this;
  70326. }
  70327. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70328. //-- Begin properties for backward compatibility for inputs
  70329. get: function () {
  70330. var touch = this.inputs.attached["touch"];
  70331. if (touch)
  70332. return touch.touchAngularSensibility;
  70333. return 0;
  70334. },
  70335. set: function (value) {
  70336. var touch = this.inputs.attached["touch"];
  70337. if (touch)
  70338. touch.touchAngularSensibility = value;
  70339. },
  70340. enumerable: true,
  70341. configurable: true
  70342. });
  70343. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70344. get: function () {
  70345. var touch = this.inputs.attached["touch"];
  70346. if (touch)
  70347. return touch.touchMoveSensibility;
  70348. return 0;
  70349. },
  70350. set: function (value) {
  70351. var touch = this.inputs.attached["touch"];
  70352. if (touch)
  70353. touch.touchMoveSensibility = value;
  70354. },
  70355. enumerable: true,
  70356. configurable: true
  70357. });
  70358. TouchCamera.prototype.getClassName = function () {
  70359. return "TouchCamera";
  70360. };
  70361. TouchCamera.prototype._setupInputs = function () {
  70362. var mouse = this.inputs.attached["mouse"];
  70363. if (mouse) {
  70364. mouse.touchEnabled = false;
  70365. }
  70366. };
  70367. return TouchCamera;
  70368. }(BABYLON.FreeCamera));
  70369. BABYLON.TouchCamera = TouchCamera;
  70370. })(BABYLON || (BABYLON = {}));
  70371. //# sourceMappingURL=babylon.touchCamera.js.map
  70372. var BABYLON;
  70373. (function (BABYLON) {
  70374. var ProceduralTexture = /** @class */ (function (_super) {
  70375. __extends(ProceduralTexture, _super);
  70376. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70377. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70378. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70379. if (isCube === void 0) { isCube = false; }
  70380. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70381. _this.isCube = isCube;
  70382. _this.isEnabled = true;
  70383. _this._currentRefreshId = -1;
  70384. _this._refreshRate = 1;
  70385. _this._vertexBuffers = {};
  70386. _this._uniforms = new Array();
  70387. _this._samplers = new Array();
  70388. _this._textures = {};
  70389. _this._floats = {};
  70390. _this._floatsArrays = {};
  70391. _this._colors3 = {};
  70392. _this._colors4 = {};
  70393. _this._vectors2 = {};
  70394. _this._vectors3 = {};
  70395. _this._matrices = {};
  70396. _this._fallbackTextureUsed = false;
  70397. scene.proceduralTextures.push(_this);
  70398. _this._engine = scene.getEngine();
  70399. _this.name = name;
  70400. _this.isRenderTarget = true;
  70401. _this._size = size;
  70402. _this._generateMipMaps = generateMipMaps;
  70403. _this.setFragment(fragment);
  70404. _this._fallbackTexture = fallbackTexture;
  70405. if (isCube) {
  70406. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70407. _this.setFloat("face", 0);
  70408. }
  70409. else {
  70410. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70411. }
  70412. // VBO
  70413. var vertices = [];
  70414. vertices.push(1, 1);
  70415. vertices.push(-1, 1);
  70416. vertices.push(-1, -1);
  70417. vertices.push(1, -1);
  70418. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70419. _this._createIndexBuffer();
  70420. return _this;
  70421. }
  70422. ProceduralTexture.prototype._createIndexBuffer = function () {
  70423. var engine = this._engine;
  70424. // Indices
  70425. var indices = [];
  70426. indices.push(0);
  70427. indices.push(1);
  70428. indices.push(2);
  70429. indices.push(0);
  70430. indices.push(2);
  70431. indices.push(3);
  70432. this._indexBuffer = engine.createIndexBuffer(indices);
  70433. };
  70434. ProceduralTexture.prototype._rebuild = function () {
  70435. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70436. if (vb) {
  70437. vb._rebuild();
  70438. }
  70439. this._createIndexBuffer();
  70440. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70441. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70442. }
  70443. };
  70444. ProceduralTexture.prototype.reset = function () {
  70445. if (this._effect === undefined) {
  70446. return;
  70447. }
  70448. var engine = this._engine;
  70449. engine._releaseEffect(this._effect);
  70450. };
  70451. ProceduralTexture.prototype.isReady = function () {
  70452. var _this = this;
  70453. var engine = this._engine;
  70454. var shaders;
  70455. if (!this._fragment) {
  70456. return false;
  70457. }
  70458. if (this._fallbackTextureUsed) {
  70459. return true;
  70460. }
  70461. if (this._fragment.fragmentElement !== undefined) {
  70462. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70463. }
  70464. else {
  70465. shaders = { vertex: "procedural", fragment: this._fragment };
  70466. }
  70467. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70468. _this.releaseInternalTexture();
  70469. if (_this._fallbackTexture) {
  70470. _this._texture = _this._fallbackTexture._texture;
  70471. if (_this._texture) {
  70472. _this._texture.incrementReferences();
  70473. }
  70474. }
  70475. _this._fallbackTextureUsed = true;
  70476. });
  70477. return this._effect.isReady();
  70478. };
  70479. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70480. this._currentRefreshId = -1;
  70481. };
  70482. ProceduralTexture.prototype.setFragment = function (fragment) {
  70483. this._fragment = fragment;
  70484. };
  70485. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70486. get: function () {
  70487. return this._refreshRate;
  70488. },
  70489. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70490. set: function (value) {
  70491. this._refreshRate = value;
  70492. this.resetRefreshCounter();
  70493. },
  70494. enumerable: true,
  70495. configurable: true
  70496. });
  70497. ProceduralTexture.prototype._shouldRender = function () {
  70498. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70499. return false;
  70500. }
  70501. if (this._fallbackTextureUsed) {
  70502. return false;
  70503. }
  70504. if (this._currentRefreshId === -1) { // At least render once
  70505. this._currentRefreshId = 1;
  70506. return true;
  70507. }
  70508. if (this.refreshRate === this._currentRefreshId) {
  70509. this._currentRefreshId = 1;
  70510. return true;
  70511. }
  70512. this._currentRefreshId++;
  70513. return false;
  70514. };
  70515. ProceduralTexture.prototype.getRenderSize = function () {
  70516. return this._size;
  70517. };
  70518. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70519. if (this._fallbackTextureUsed) {
  70520. return;
  70521. }
  70522. this.releaseInternalTexture();
  70523. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70524. };
  70525. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70526. if (this._uniforms.indexOf(uniformName) === -1) {
  70527. this._uniforms.push(uniformName);
  70528. }
  70529. };
  70530. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70531. if (this._samplers.indexOf(name) === -1) {
  70532. this._samplers.push(name);
  70533. }
  70534. this._textures[name] = texture;
  70535. return this;
  70536. };
  70537. ProceduralTexture.prototype.setFloat = function (name, value) {
  70538. this._checkUniform(name);
  70539. this._floats[name] = value;
  70540. return this;
  70541. };
  70542. ProceduralTexture.prototype.setFloats = function (name, value) {
  70543. this._checkUniform(name);
  70544. this._floatsArrays[name] = value;
  70545. return this;
  70546. };
  70547. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70548. this._checkUniform(name);
  70549. this._colors3[name] = value;
  70550. return this;
  70551. };
  70552. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70553. this._checkUniform(name);
  70554. this._colors4[name] = value;
  70555. return this;
  70556. };
  70557. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70558. this._checkUniform(name);
  70559. this._vectors2[name] = value;
  70560. return this;
  70561. };
  70562. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70563. this._checkUniform(name);
  70564. this._vectors3[name] = value;
  70565. return this;
  70566. };
  70567. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70568. this._checkUniform(name);
  70569. this._matrices[name] = value;
  70570. return this;
  70571. };
  70572. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70573. var scene = this.getScene();
  70574. if (!scene) {
  70575. return;
  70576. }
  70577. var engine = this._engine;
  70578. // Render
  70579. engine.enableEffect(this._effect);
  70580. engine.setState(false);
  70581. // Texture
  70582. for (var name in this._textures) {
  70583. this._effect.setTexture(name, this._textures[name]);
  70584. }
  70585. // Float
  70586. for (name in this._floats) {
  70587. this._effect.setFloat(name, this._floats[name]);
  70588. }
  70589. // Floats
  70590. for (name in this._floatsArrays) {
  70591. this._effect.setArray(name, this._floatsArrays[name]);
  70592. }
  70593. // Color3
  70594. for (name in this._colors3) {
  70595. this._effect.setColor3(name, this._colors3[name]);
  70596. }
  70597. // Color4
  70598. for (name in this._colors4) {
  70599. var color = this._colors4[name];
  70600. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70601. }
  70602. // Vector2
  70603. for (name in this._vectors2) {
  70604. this._effect.setVector2(name, this._vectors2[name]);
  70605. }
  70606. // Vector3
  70607. for (name in this._vectors3) {
  70608. this._effect.setVector3(name, this._vectors3[name]);
  70609. }
  70610. // Matrix
  70611. for (name in this._matrices) {
  70612. this._effect.setMatrix(name, this._matrices[name]);
  70613. }
  70614. if (!this._texture) {
  70615. return;
  70616. }
  70617. if (this.isCube) {
  70618. for (var face = 0; face < 6; face++) {
  70619. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70620. // VBOs
  70621. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70622. this._effect.setFloat("face", face);
  70623. // Clear
  70624. engine.clear(scene.clearColor, true, true, true);
  70625. // Draw order
  70626. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70627. // Mipmaps
  70628. if (face === 5) {
  70629. engine.generateMipMapsForCubemap(this._texture);
  70630. }
  70631. }
  70632. }
  70633. else {
  70634. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70635. // VBOs
  70636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70637. // Clear
  70638. engine.clear(scene.clearColor, true, true, true);
  70639. // Draw order
  70640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70641. }
  70642. // Unbind
  70643. engine.unBindFramebuffer(this._texture, this.isCube);
  70644. if (this.onGenerated) {
  70645. this.onGenerated();
  70646. }
  70647. };
  70648. ProceduralTexture.prototype.clone = function () {
  70649. var textureSize = this.getSize();
  70650. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70651. // Base texture
  70652. newTexture.hasAlpha = this.hasAlpha;
  70653. newTexture.level = this.level;
  70654. // RenderTarget Texture
  70655. newTexture.coordinatesMode = this.coordinatesMode;
  70656. return newTexture;
  70657. };
  70658. ProceduralTexture.prototype.dispose = function () {
  70659. var scene = this.getScene();
  70660. if (!scene) {
  70661. return;
  70662. }
  70663. var index = scene.proceduralTextures.indexOf(this);
  70664. if (index >= 0) {
  70665. scene.proceduralTextures.splice(index, 1);
  70666. }
  70667. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70668. if (vertexBuffer) {
  70669. vertexBuffer.dispose();
  70670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70671. }
  70672. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70673. this._indexBuffer = null;
  70674. }
  70675. _super.prototype.dispose.call(this);
  70676. };
  70677. return ProceduralTexture;
  70678. }(BABYLON.Texture));
  70679. BABYLON.ProceduralTexture = ProceduralTexture;
  70680. })(BABYLON || (BABYLON = {}));
  70681. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70682. var BABYLON;
  70683. (function (BABYLON) {
  70684. var CustomProceduralTexture = /** @class */ (function (_super) {
  70685. __extends(CustomProceduralTexture, _super);
  70686. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70687. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70688. _this._animate = true;
  70689. _this._time = 0;
  70690. _this._texturePath = texturePath;
  70691. //Try to load json
  70692. _this.loadJson(texturePath);
  70693. _this.refreshRate = 1;
  70694. return _this;
  70695. }
  70696. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70697. var _this = this;
  70698. var noConfigFile = function () {
  70699. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70700. try {
  70701. _this.setFragment(_this._texturePath);
  70702. }
  70703. catch (ex) {
  70704. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70705. }
  70706. };
  70707. var configFileUrl = jsonUrl + "/config.json";
  70708. var xhr = new XMLHttpRequest();
  70709. xhr.open("GET", configFileUrl, true);
  70710. xhr.addEventListener("load", function () {
  70711. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70712. try {
  70713. _this._config = JSON.parse(xhr.response);
  70714. _this.updateShaderUniforms();
  70715. _this.updateTextures();
  70716. _this.setFragment(_this._texturePath + "/custom");
  70717. _this._animate = _this._config.animate;
  70718. _this.refreshRate = _this._config.refreshrate;
  70719. }
  70720. catch (ex) {
  70721. noConfigFile();
  70722. }
  70723. }
  70724. else {
  70725. noConfigFile();
  70726. }
  70727. }, false);
  70728. xhr.addEventListener("error", function () {
  70729. noConfigFile();
  70730. }, false);
  70731. try {
  70732. xhr.send();
  70733. }
  70734. catch (ex) {
  70735. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70736. }
  70737. };
  70738. CustomProceduralTexture.prototype.isReady = function () {
  70739. if (!_super.prototype.isReady.call(this)) {
  70740. return false;
  70741. }
  70742. for (var name in this._textures) {
  70743. var texture = this._textures[name];
  70744. if (!texture.isReady()) {
  70745. return false;
  70746. }
  70747. }
  70748. return true;
  70749. };
  70750. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70751. var scene = this.getScene();
  70752. if (this._animate && scene) {
  70753. this._time += scene.getAnimationRatio() * 0.03;
  70754. this.updateShaderUniforms();
  70755. }
  70756. _super.prototype.render.call(this, useCameraPostProcess);
  70757. };
  70758. CustomProceduralTexture.prototype.updateTextures = function () {
  70759. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70760. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70761. }
  70762. };
  70763. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70764. if (this._config) {
  70765. for (var j = 0; j < this._config.uniforms.length; j++) {
  70766. var uniform = this._config.uniforms[j];
  70767. switch (uniform.type) {
  70768. case "float":
  70769. this.setFloat(uniform.name, uniform.value);
  70770. break;
  70771. case "color3":
  70772. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70773. break;
  70774. case "color4":
  70775. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70776. break;
  70777. case "vector2":
  70778. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70779. break;
  70780. case "vector3":
  70781. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70782. break;
  70783. }
  70784. }
  70785. }
  70786. this.setFloat("time", this._time);
  70787. };
  70788. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70789. get: function () {
  70790. return this._animate;
  70791. },
  70792. set: function (value) {
  70793. this._animate = value;
  70794. },
  70795. enumerable: true,
  70796. configurable: true
  70797. });
  70798. return CustomProceduralTexture;
  70799. }(BABYLON.ProceduralTexture));
  70800. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70801. })(BABYLON || (BABYLON = {}));
  70802. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70803. var BABYLON;
  70804. (function (BABYLON) {
  70805. var FreeCameraGamepadInput = /** @class */ (function () {
  70806. function FreeCameraGamepadInput() {
  70807. this.gamepadAngularSensibility = 200;
  70808. this.gamepadMoveSensibility = 40;
  70809. // private members
  70810. this._cameraTransform = BABYLON.Matrix.Identity();
  70811. this._deltaTransform = BABYLON.Vector3.Zero();
  70812. this._vector3 = BABYLON.Vector3.Zero();
  70813. this._vector2 = BABYLON.Vector2.Zero();
  70814. }
  70815. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70816. var _this = this;
  70817. var manager = this.camera.getScene().gamepadManager;
  70818. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70819. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70820. // prioritize XBOX gamepads.
  70821. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70822. _this.gamepad = gamepad;
  70823. }
  70824. }
  70825. });
  70826. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70827. if (_this.gamepad === gamepad) {
  70828. _this.gamepad = null;
  70829. }
  70830. });
  70831. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70832. };
  70833. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70834. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70835. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70836. this.gamepad = null;
  70837. };
  70838. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70839. if (this.gamepad && this.gamepad.leftStick) {
  70840. var camera = this.camera;
  70841. var LSValues = this.gamepad.leftStick;
  70842. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70843. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70844. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70845. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70846. var RSValues = this.gamepad.rightStick;
  70847. if (RSValues) {
  70848. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70849. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70850. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70851. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70852. }
  70853. else {
  70854. RSValues = { x: 0, y: 0 };
  70855. }
  70856. if (!camera.rotationQuaternion) {
  70857. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70858. }
  70859. else {
  70860. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70861. }
  70862. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70863. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70864. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70865. camera.cameraDirection.addInPlace(this._deltaTransform);
  70866. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70867. camera.cameraRotation.addInPlace(this._vector2);
  70868. }
  70869. };
  70870. FreeCameraGamepadInput.prototype.getClassName = function () {
  70871. return "FreeCameraGamepadInput";
  70872. };
  70873. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70874. return "gamepad";
  70875. };
  70876. __decorate([
  70877. BABYLON.serialize()
  70878. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70879. __decorate([
  70880. BABYLON.serialize()
  70881. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70882. return FreeCameraGamepadInput;
  70883. }());
  70884. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70885. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70886. })(BABYLON || (BABYLON = {}));
  70887. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70888. var BABYLON;
  70889. (function (BABYLON) {
  70890. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70891. function ArcRotateCameraGamepadInput() {
  70892. this.gamepadRotationSensibility = 80;
  70893. this.gamepadMoveSensibility = 40;
  70894. }
  70895. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70896. var _this = this;
  70897. var manager = this.camera.getScene().gamepadManager;
  70898. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70899. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70900. // prioritize XBOX gamepads.
  70901. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70902. _this.gamepad = gamepad;
  70903. }
  70904. }
  70905. });
  70906. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70907. if (_this.gamepad === gamepad) {
  70908. _this.gamepad = null;
  70909. }
  70910. });
  70911. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70912. };
  70913. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70914. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70915. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70916. this.gamepad = null;
  70917. };
  70918. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70919. if (this.gamepad) {
  70920. var camera = this.camera;
  70921. var RSValues = this.gamepad.rightStick;
  70922. if (RSValues) {
  70923. if (RSValues.x != 0) {
  70924. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70925. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70926. camera.inertialAlphaOffset += normalizedRX;
  70927. }
  70928. }
  70929. if (RSValues.y != 0) {
  70930. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70931. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70932. camera.inertialBetaOffset += normalizedRY;
  70933. }
  70934. }
  70935. }
  70936. var LSValues = this.gamepad.leftStick;
  70937. if (LSValues && LSValues.y != 0) {
  70938. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70939. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70940. this.camera.inertialRadiusOffset -= normalizedLY;
  70941. }
  70942. }
  70943. }
  70944. };
  70945. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70946. return "ArcRotateCameraGamepadInput";
  70947. };
  70948. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70949. return "gamepad";
  70950. };
  70951. __decorate([
  70952. BABYLON.serialize()
  70953. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70954. __decorate([
  70955. BABYLON.serialize()
  70956. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70957. return ArcRotateCameraGamepadInput;
  70958. }());
  70959. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70960. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70961. })(BABYLON || (BABYLON = {}));
  70962. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70963. var BABYLON;
  70964. (function (BABYLON) {
  70965. var GamepadManager = /** @class */ (function () {
  70966. function GamepadManager(_scene) {
  70967. var _this = this;
  70968. this._scene = _scene;
  70969. this._babylonGamepads = [];
  70970. this._oneGamepadConnected = false;
  70971. this._isMonitoring = false;
  70972. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70973. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70974. this._gamepadEventSupported = false;
  70975. }
  70976. else {
  70977. this._gamepadEventSupported = 'GamepadEvent' in window;
  70978. this._gamepadSupport = (navigator.getGamepads ||
  70979. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70980. }
  70981. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70982. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70983. for (var i in _this._babylonGamepads) {
  70984. var gamepad = _this._babylonGamepads[i];
  70985. if (gamepad && gamepad._isConnected) {
  70986. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70987. }
  70988. }
  70989. });
  70990. this._onGamepadConnectedEvent = function (evt) {
  70991. var gamepad = evt.gamepad;
  70992. if (gamepad.index in _this._babylonGamepads) {
  70993. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70994. return;
  70995. }
  70996. }
  70997. var newGamepad;
  70998. if (_this._babylonGamepads[gamepad.index]) {
  70999. newGamepad = _this._babylonGamepads[gamepad.index];
  71000. newGamepad.browserGamepad = gamepad;
  71001. newGamepad._isConnected = true;
  71002. }
  71003. else {
  71004. newGamepad = _this._addNewGamepad(gamepad);
  71005. }
  71006. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71007. _this._startMonitoringGamepads();
  71008. };
  71009. this._onGamepadDisconnectedEvent = function (evt) {
  71010. var gamepad = evt.gamepad;
  71011. // Remove the gamepad from the list of gamepads to monitor.
  71012. for (var i in _this._babylonGamepads) {
  71013. if (_this._babylonGamepads[i].index === gamepad.index) {
  71014. var disconnectedGamepad = _this._babylonGamepads[i];
  71015. disconnectedGamepad._isConnected = false;
  71016. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71017. break;
  71018. }
  71019. }
  71020. };
  71021. if (this._gamepadSupport) {
  71022. //first add already-connected gamepads
  71023. this._updateGamepadObjects();
  71024. if (this._babylonGamepads.length) {
  71025. this._startMonitoringGamepads();
  71026. }
  71027. // Checking if the gamepad connected event is supported (like in Firefox)
  71028. if (this._gamepadEventSupported) {
  71029. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71030. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71031. }
  71032. else {
  71033. this._startMonitoringGamepads();
  71034. }
  71035. }
  71036. }
  71037. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71038. get: function () {
  71039. return this._babylonGamepads;
  71040. },
  71041. enumerable: true,
  71042. configurable: true
  71043. });
  71044. GamepadManager.prototype.getGamepadByType = function (type) {
  71045. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71046. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71047. var gamepad = _a[_i];
  71048. if (gamepad && gamepad.type === type) {
  71049. return gamepad;
  71050. }
  71051. }
  71052. return null;
  71053. };
  71054. GamepadManager.prototype.dispose = function () {
  71055. if (this._gamepadEventSupported) {
  71056. if (this._onGamepadConnectedEvent) {
  71057. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71058. }
  71059. if (this._onGamepadDisconnectedEvent) {
  71060. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71061. }
  71062. this._onGamepadConnectedEvent = null;
  71063. this._onGamepadDisconnectedEvent = null;
  71064. }
  71065. this._babylonGamepads.forEach(function (gamepad) {
  71066. gamepad.dispose();
  71067. });
  71068. this.onGamepadConnectedObservable.clear();
  71069. this.onGamepadDisconnectedObservable.clear();
  71070. this._oneGamepadConnected = false;
  71071. this._stopMonitoringGamepads();
  71072. this._babylonGamepads = [];
  71073. };
  71074. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71075. if (!this._oneGamepadConnected) {
  71076. this._oneGamepadConnected = true;
  71077. }
  71078. var newGamepad;
  71079. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71080. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71081. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71082. }
  71083. // if pose is supported, use the (WebVR) pose enabled controller
  71084. else if (gamepad.pose) {
  71085. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71086. }
  71087. else {
  71088. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71089. }
  71090. this._babylonGamepads[newGamepad.index] = newGamepad;
  71091. return newGamepad;
  71092. };
  71093. GamepadManager.prototype._startMonitoringGamepads = function () {
  71094. if (!this._isMonitoring) {
  71095. this._isMonitoring = true;
  71096. //back-comp
  71097. if (!this._scene) {
  71098. this._checkGamepadsStatus();
  71099. }
  71100. }
  71101. };
  71102. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71103. this._isMonitoring = false;
  71104. };
  71105. GamepadManager.prototype._checkGamepadsStatus = function () {
  71106. var _this = this;
  71107. // Hack to be compatible Chrome
  71108. this._updateGamepadObjects();
  71109. for (var i in this._babylonGamepads) {
  71110. var gamepad = this._babylonGamepads[i];
  71111. if (!gamepad || !gamepad.isConnected) {
  71112. continue;
  71113. }
  71114. gamepad.update();
  71115. }
  71116. if (this._isMonitoring && !this._scene) {
  71117. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71118. }
  71119. };
  71120. // This function is called only on Chrome, which does not properly support
  71121. // connection/disconnection events and forces you to recopy again the gamepad object
  71122. GamepadManager.prototype._updateGamepadObjects = function () {
  71123. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71124. for (var i = 0; i < gamepads.length; i++) {
  71125. var gamepad = gamepads[i];
  71126. if (gamepad) {
  71127. if (!this._babylonGamepads[gamepad.index]) {
  71128. var newGamepad = this._addNewGamepad(gamepad);
  71129. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71130. }
  71131. else {
  71132. // Forced to copy again this object for Chrome for unknown reason
  71133. this._babylonGamepads[i].browserGamepad = gamepad;
  71134. if (!this._babylonGamepads[i].isConnected) {
  71135. this._babylonGamepads[i]._isConnected = true;
  71136. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71137. }
  71138. }
  71139. }
  71140. }
  71141. };
  71142. return GamepadManager;
  71143. }());
  71144. BABYLON.GamepadManager = GamepadManager;
  71145. })(BABYLON || (BABYLON = {}));
  71146. //# sourceMappingURL=babylon.gamepadManager.js.map
  71147. var BABYLON;
  71148. (function (BABYLON) {
  71149. var StickValues = /** @class */ (function () {
  71150. function StickValues(x, y) {
  71151. this.x = x;
  71152. this.y = y;
  71153. }
  71154. return StickValues;
  71155. }());
  71156. BABYLON.StickValues = StickValues;
  71157. var Gamepad = /** @class */ (function () {
  71158. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71159. if (leftStickX === void 0) { leftStickX = 0; }
  71160. if (leftStickY === void 0) { leftStickY = 1; }
  71161. if (rightStickX === void 0) { rightStickX = 2; }
  71162. if (rightStickY === void 0) { rightStickY = 3; }
  71163. this.id = id;
  71164. this.index = index;
  71165. this.browserGamepad = browserGamepad;
  71166. this._isConnected = true;
  71167. this._invertLeftStickY = false;
  71168. this.type = Gamepad.GAMEPAD;
  71169. this._leftStickAxisX = leftStickX;
  71170. this._leftStickAxisY = leftStickY;
  71171. this._rightStickAxisX = rightStickX;
  71172. this._rightStickAxisY = rightStickY;
  71173. if (this.browserGamepad.axes.length >= 2) {
  71174. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71175. }
  71176. if (this.browserGamepad.axes.length >= 4) {
  71177. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71178. }
  71179. }
  71180. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71181. get: function () {
  71182. return this._isConnected;
  71183. },
  71184. enumerable: true,
  71185. configurable: true
  71186. });
  71187. Gamepad.prototype.onleftstickchanged = function (callback) {
  71188. this._onleftstickchanged = callback;
  71189. };
  71190. Gamepad.prototype.onrightstickchanged = function (callback) {
  71191. this._onrightstickchanged = callback;
  71192. };
  71193. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71194. get: function () {
  71195. return this._leftStick;
  71196. },
  71197. set: function (newValues) {
  71198. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71199. this._onleftstickchanged(newValues);
  71200. }
  71201. this._leftStick = newValues;
  71202. },
  71203. enumerable: true,
  71204. configurable: true
  71205. });
  71206. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71207. get: function () {
  71208. return this._rightStick;
  71209. },
  71210. set: function (newValues) {
  71211. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71212. this._onrightstickchanged(newValues);
  71213. }
  71214. this._rightStick = newValues;
  71215. },
  71216. enumerable: true,
  71217. configurable: true
  71218. });
  71219. Gamepad.prototype.update = function () {
  71220. if (this._leftStick) {
  71221. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71222. if (this._invertLeftStickY) {
  71223. this.leftStick.y *= -1;
  71224. }
  71225. }
  71226. if (this._rightStick) {
  71227. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71228. }
  71229. };
  71230. Gamepad.prototype.dispose = function () {
  71231. };
  71232. Gamepad.GAMEPAD = 0;
  71233. Gamepad.GENERIC = 1;
  71234. Gamepad.XBOX = 2;
  71235. Gamepad.POSE_ENABLED = 3;
  71236. return Gamepad;
  71237. }());
  71238. BABYLON.Gamepad = Gamepad;
  71239. var GenericPad = /** @class */ (function (_super) {
  71240. __extends(GenericPad, _super);
  71241. function GenericPad(id, index, browserGamepad) {
  71242. var _this = _super.call(this, id, index, browserGamepad) || this;
  71243. _this.onButtonDownObservable = new BABYLON.Observable();
  71244. _this.onButtonUpObservable = new BABYLON.Observable();
  71245. _this.type = Gamepad.GENERIC;
  71246. _this._buttons = new Array(browserGamepad.buttons.length);
  71247. return _this;
  71248. }
  71249. GenericPad.prototype.onbuttondown = function (callback) {
  71250. this._onbuttondown = callback;
  71251. };
  71252. GenericPad.prototype.onbuttonup = function (callback) {
  71253. this._onbuttonup = callback;
  71254. };
  71255. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71256. if (newValue !== currentValue) {
  71257. if (newValue === 1) {
  71258. if (this._onbuttondown) {
  71259. this._onbuttondown(buttonIndex);
  71260. }
  71261. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71262. }
  71263. if (newValue === 0) {
  71264. if (this._onbuttonup) {
  71265. this._onbuttonup(buttonIndex);
  71266. }
  71267. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71268. }
  71269. }
  71270. return newValue;
  71271. };
  71272. GenericPad.prototype.update = function () {
  71273. _super.prototype.update.call(this);
  71274. for (var index = 0; index < this._buttons.length; index++) {
  71275. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71276. }
  71277. };
  71278. GenericPad.prototype.dispose = function () {
  71279. _super.prototype.dispose.call(this);
  71280. this.onButtonDownObservable.clear();
  71281. this.onButtonUpObservable.clear();
  71282. };
  71283. return GenericPad;
  71284. }(Gamepad));
  71285. BABYLON.GenericPad = GenericPad;
  71286. })(BABYLON || (BABYLON = {}));
  71287. //# sourceMappingURL=babylon.gamepad.js.map
  71288. var BABYLON;
  71289. (function (BABYLON) {
  71290. /**
  71291. * Defines supported buttons for XBox360 compatible gamepads
  71292. */
  71293. var Xbox360Button;
  71294. (function (Xbox360Button) {
  71295. /** A */
  71296. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71297. /** B */
  71298. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71299. /** X */
  71300. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71301. /** Y */
  71302. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71303. /** Start */
  71304. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71305. /** Back */
  71306. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71307. /** Left button */
  71308. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71309. /** Right button */
  71310. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71311. /** Left stick */
  71312. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71313. /** Right stick */
  71314. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71315. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71316. /** Defines values for XBox360 DPad */
  71317. var Xbox360Dpad;
  71318. (function (Xbox360Dpad) {
  71319. /** Up */
  71320. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71321. /** Down */
  71322. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71323. /** Left */
  71324. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71325. /** Right */
  71326. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71327. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71328. /**
  71329. * Defines a XBox360 gamepad
  71330. */
  71331. var Xbox360Pad = /** @class */ (function (_super) {
  71332. __extends(Xbox360Pad, _super);
  71333. /**
  71334. * Creates a new XBox360 gamepad object
  71335. * @param id defines the id of this gamepad
  71336. * @param index defines its index
  71337. * @param gamepad defines the internal HTML gamepad object
  71338. * @param xboxOne defines if it is a XBox One gamepad
  71339. */
  71340. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71341. if (xboxOne === void 0) { xboxOne = false; }
  71342. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71343. _this._leftTrigger = 0;
  71344. _this._rightTrigger = 0;
  71345. /** Observable raised when a button is pressed */
  71346. _this.onButtonDownObservable = new BABYLON.Observable();
  71347. /** Observable raised when a button is released */
  71348. _this.onButtonUpObservable = new BABYLON.Observable();
  71349. /** Observable raised when a pad is pressed */
  71350. _this.onPadDownObservable = new BABYLON.Observable();
  71351. /** Observable raised when a pad is released */
  71352. _this.onPadUpObservable = new BABYLON.Observable();
  71353. _this._buttonA = 0;
  71354. _this._buttonB = 0;
  71355. _this._buttonX = 0;
  71356. _this._buttonY = 0;
  71357. _this._buttonBack = 0;
  71358. _this._buttonStart = 0;
  71359. _this._buttonLB = 0;
  71360. _this._buttonRB = 0;
  71361. _this._buttonLeftStick = 0;
  71362. _this._buttonRightStick = 0;
  71363. _this._dPadUp = 0;
  71364. _this._dPadDown = 0;
  71365. _this._dPadLeft = 0;
  71366. _this._dPadRight = 0;
  71367. _this._isXboxOnePad = false;
  71368. _this.type = BABYLON.Gamepad.XBOX;
  71369. _this._isXboxOnePad = xboxOne;
  71370. return _this;
  71371. }
  71372. /**
  71373. * Defines the callback to call when left trigger is pressed
  71374. * @param callback defines the callback to use
  71375. */
  71376. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71377. this._onlefttriggerchanged = callback;
  71378. };
  71379. /**
  71380. * Defines the callback to call when right trigger is pressed
  71381. * @param callback defines the callback to use
  71382. */
  71383. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71384. this._onrighttriggerchanged = callback;
  71385. };
  71386. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71387. /**
  71388. * Gets or sets left trigger value
  71389. */
  71390. get: function () {
  71391. return this._leftTrigger;
  71392. },
  71393. set: function (newValue) {
  71394. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71395. this._onlefttriggerchanged(newValue);
  71396. }
  71397. this._leftTrigger = newValue;
  71398. },
  71399. enumerable: true,
  71400. configurable: true
  71401. });
  71402. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71403. /**
  71404. * Gets or sets right trigger value
  71405. */
  71406. get: function () {
  71407. return this._rightTrigger;
  71408. },
  71409. set: function (newValue) {
  71410. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71411. this._onrighttriggerchanged(newValue);
  71412. }
  71413. this._rightTrigger = newValue;
  71414. },
  71415. enumerable: true,
  71416. configurable: true
  71417. });
  71418. /**
  71419. * Defines the callback to call when a button is pressed
  71420. * @param callback defines the callback to use
  71421. */
  71422. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71423. this._onbuttondown = callback;
  71424. };
  71425. /**
  71426. * Defines the callback to call when a button is released
  71427. * @param callback defines the callback to use
  71428. */
  71429. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71430. this._onbuttonup = callback;
  71431. };
  71432. /**
  71433. * Defines the callback to call when a pad is pressed
  71434. * @param callback defines the callback to use
  71435. */
  71436. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71437. this._ondpaddown = callback;
  71438. };
  71439. /**
  71440. * Defines the callback to call when a pad is released
  71441. * @param callback defines the callback to use
  71442. */
  71443. Xbox360Pad.prototype.ondpadup = function (callback) {
  71444. this._ondpadup = callback;
  71445. };
  71446. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71447. if (newValue !== currentValue) {
  71448. if (newValue === 1) {
  71449. if (this._onbuttondown) {
  71450. this._onbuttondown(buttonType);
  71451. }
  71452. this.onButtonDownObservable.notifyObservers(buttonType);
  71453. }
  71454. if (newValue === 0) {
  71455. if (this._onbuttonup) {
  71456. this._onbuttonup(buttonType);
  71457. }
  71458. this.onButtonUpObservable.notifyObservers(buttonType);
  71459. }
  71460. }
  71461. return newValue;
  71462. };
  71463. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71464. if (newValue !== currentValue) {
  71465. if (newValue === 1) {
  71466. if (this._ondpaddown) {
  71467. this._ondpaddown(buttonType);
  71468. }
  71469. this.onPadDownObservable.notifyObservers(buttonType);
  71470. }
  71471. if (newValue === 0) {
  71472. if (this._ondpadup) {
  71473. this._ondpadup(buttonType);
  71474. }
  71475. this.onPadUpObservable.notifyObservers(buttonType);
  71476. }
  71477. }
  71478. return newValue;
  71479. };
  71480. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71481. /** Gets or sets value of A button */
  71482. get: function () {
  71483. return this._buttonA;
  71484. },
  71485. set: function (value) {
  71486. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71487. },
  71488. enumerable: true,
  71489. configurable: true
  71490. });
  71491. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71492. /** Gets or sets value of B button */
  71493. get: function () {
  71494. return this._buttonB;
  71495. },
  71496. set: function (value) {
  71497. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71498. },
  71499. enumerable: true,
  71500. configurable: true
  71501. });
  71502. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71503. /** Gets or sets value of X button */
  71504. get: function () {
  71505. return this._buttonX;
  71506. },
  71507. set: function (value) {
  71508. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71509. },
  71510. enumerable: true,
  71511. configurable: true
  71512. });
  71513. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71514. /** Gets or sets value of Y button */
  71515. get: function () {
  71516. return this._buttonY;
  71517. },
  71518. set: function (value) {
  71519. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71520. },
  71521. enumerable: true,
  71522. configurable: true
  71523. });
  71524. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71525. /** Gets or sets value of Start button */
  71526. get: function () {
  71527. return this._buttonStart;
  71528. },
  71529. set: function (value) {
  71530. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71531. },
  71532. enumerable: true,
  71533. configurable: true
  71534. });
  71535. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71536. /** Gets or sets value of Back button */
  71537. get: function () {
  71538. return this._buttonBack;
  71539. },
  71540. set: function (value) {
  71541. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71542. },
  71543. enumerable: true,
  71544. configurable: true
  71545. });
  71546. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71547. /** Gets or sets value of Left button */
  71548. get: function () {
  71549. return this._buttonLB;
  71550. },
  71551. set: function (value) {
  71552. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71553. },
  71554. enumerable: true,
  71555. configurable: true
  71556. });
  71557. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71558. /** Gets or sets value of Right button */
  71559. get: function () {
  71560. return this._buttonRB;
  71561. },
  71562. set: function (value) {
  71563. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71564. },
  71565. enumerable: true,
  71566. configurable: true
  71567. });
  71568. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71569. /** Gets or sets value of left stick */
  71570. get: function () {
  71571. return this._buttonLeftStick;
  71572. },
  71573. set: function (value) {
  71574. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71575. },
  71576. enumerable: true,
  71577. configurable: true
  71578. });
  71579. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71580. /** Gets or sets value of right stick */
  71581. get: function () {
  71582. return this._buttonRightStick;
  71583. },
  71584. set: function (value) {
  71585. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71586. },
  71587. enumerable: true,
  71588. configurable: true
  71589. });
  71590. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71591. /** Gets or sets value of DPad up */
  71592. get: function () {
  71593. return this._dPadUp;
  71594. },
  71595. set: function (value) {
  71596. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71602. /** Gets or sets value of DPad down */
  71603. get: function () {
  71604. return this._dPadDown;
  71605. },
  71606. set: function (value) {
  71607. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71608. },
  71609. enumerable: true,
  71610. configurable: true
  71611. });
  71612. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71613. /** Gets or sets value of DPad left */
  71614. get: function () {
  71615. return this._dPadLeft;
  71616. },
  71617. set: function (value) {
  71618. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71619. },
  71620. enumerable: true,
  71621. configurable: true
  71622. });
  71623. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71624. /** Gets or sets value of DPad right */
  71625. get: function () {
  71626. return this._dPadRight;
  71627. },
  71628. set: function (value) {
  71629. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71630. },
  71631. enumerable: true,
  71632. configurable: true
  71633. });
  71634. /**
  71635. * Force the gamepad to synchronize with device values
  71636. */
  71637. Xbox360Pad.prototype.update = function () {
  71638. _super.prototype.update.call(this);
  71639. if (this._isXboxOnePad) {
  71640. this.buttonA = this.browserGamepad.buttons[0].value;
  71641. this.buttonB = this.browserGamepad.buttons[1].value;
  71642. this.buttonX = this.browserGamepad.buttons[2].value;
  71643. this.buttonY = this.browserGamepad.buttons[3].value;
  71644. this.buttonLB = this.browserGamepad.buttons[4].value;
  71645. this.buttonRB = this.browserGamepad.buttons[5].value;
  71646. this.leftTrigger = this.browserGamepad.axes[2];
  71647. this.rightTrigger = this.browserGamepad.axes[5];
  71648. this.buttonBack = this.browserGamepad.buttons[9].value;
  71649. this.buttonStart = this.browserGamepad.buttons[8].value;
  71650. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71651. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71652. this.dPadUp = this.browserGamepad.buttons[11].value;
  71653. this.dPadDown = this.browserGamepad.buttons[12].value;
  71654. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71655. this.dPadRight = this.browserGamepad.buttons[14].value;
  71656. }
  71657. else {
  71658. this.buttonA = this.browserGamepad.buttons[0].value;
  71659. this.buttonB = this.browserGamepad.buttons[1].value;
  71660. this.buttonX = this.browserGamepad.buttons[2].value;
  71661. this.buttonY = this.browserGamepad.buttons[3].value;
  71662. this.buttonLB = this.browserGamepad.buttons[4].value;
  71663. this.buttonRB = this.browserGamepad.buttons[5].value;
  71664. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71665. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71666. this.buttonBack = this.browserGamepad.buttons[8].value;
  71667. this.buttonStart = this.browserGamepad.buttons[9].value;
  71668. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71669. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71670. this.dPadUp = this.browserGamepad.buttons[12].value;
  71671. this.dPadDown = this.browserGamepad.buttons[13].value;
  71672. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71673. this.dPadRight = this.browserGamepad.buttons[15].value;
  71674. }
  71675. };
  71676. Xbox360Pad.prototype.dispose = function () {
  71677. _super.prototype.dispose.call(this);
  71678. this.onButtonDownObservable.clear();
  71679. this.onButtonUpObservable.clear();
  71680. this.onPadDownObservable.clear();
  71681. this.onPadUpObservable.clear();
  71682. };
  71683. return Xbox360Pad;
  71684. }(BABYLON.Gamepad));
  71685. BABYLON.Xbox360Pad = Xbox360Pad;
  71686. })(BABYLON || (BABYLON = {}));
  71687. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71688. var BABYLON;
  71689. (function (BABYLON) {
  71690. /**
  71691. * Defines the types of pose enabled controllers that are supported
  71692. */
  71693. var PoseEnabledControllerType;
  71694. (function (PoseEnabledControllerType) {
  71695. /**
  71696. * HTC Vive
  71697. */
  71698. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71699. /**
  71700. * Oculus Rift
  71701. */
  71702. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71703. /**
  71704. * Windows mixed reality
  71705. */
  71706. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71707. /**
  71708. * Samsung gear VR
  71709. */
  71710. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71711. /**
  71712. * Google Daydream
  71713. */
  71714. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71715. /**
  71716. * Generic
  71717. */
  71718. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71719. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71720. /**
  71721. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71722. */
  71723. var PoseEnabledControllerHelper = /** @class */ (function () {
  71724. function PoseEnabledControllerHelper() {
  71725. }
  71726. /**
  71727. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71728. * @param vrGamepad the gamepad to initialized
  71729. * @returns a vr controller of the type the gamepad identified as
  71730. */
  71731. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71732. // Oculus Touch
  71733. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71734. return new BABYLON.OculusTouchController(vrGamepad);
  71735. }
  71736. // Windows Mixed Reality controllers
  71737. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71738. return new BABYLON.WindowsMotionController(vrGamepad);
  71739. }
  71740. // HTC Vive
  71741. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71742. return new BABYLON.ViveController(vrGamepad);
  71743. }
  71744. // Samsung/Oculus Gear VR or Oculus Go
  71745. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71746. return new BABYLON.GearVRController(vrGamepad);
  71747. }
  71748. // Google Daydream
  71749. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71750. return new BABYLON.DaydreamController(vrGamepad);
  71751. }
  71752. // Generic
  71753. else {
  71754. return new BABYLON.GenericController(vrGamepad);
  71755. }
  71756. };
  71757. return PoseEnabledControllerHelper;
  71758. }());
  71759. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71760. /**
  71761. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71762. */
  71763. var PoseEnabledController = /** @class */ (function (_super) {
  71764. __extends(PoseEnabledController, _super);
  71765. /**
  71766. * Creates a new PoseEnabledController from a gamepad
  71767. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71768. */
  71769. function PoseEnabledController(browserGamepad) {
  71770. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71771. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71772. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71773. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71774. /**
  71775. * The device position in babylon space
  71776. */
  71777. _this.devicePosition = BABYLON.Vector3.Zero();
  71778. /**
  71779. * The device rotation in babylon space
  71780. */
  71781. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71782. /**
  71783. * The scale factor of the device in babylon space
  71784. */
  71785. _this.deviceScaleFactor = 1;
  71786. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71787. /**
  71788. * Internal, matrix used to convert room space to babylon space
  71789. */
  71790. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71791. /**
  71792. * Node to be used when casting a ray from the controller
  71793. */
  71794. _this._pointingPoseNode = null;
  71795. _this._workingMatrix = BABYLON.Matrix.Identity();
  71796. /**
  71797. * @hidden
  71798. */
  71799. _this._meshAttachedObservable = new BABYLON.Observable();
  71800. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71801. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71802. _this.position = BABYLON.Vector3.Zero();
  71803. _this.rotationQuaternion = new BABYLON.Quaternion();
  71804. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71805. _this._calculatedRotation = new BABYLON.Quaternion();
  71806. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71807. return _this;
  71808. }
  71809. /**
  71810. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71811. */
  71812. PoseEnabledController.prototype.update = function () {
  71813. _super.prototype.update.call(this);
  71814. var pose = this.browserGamepad.pose;
  71815. this.updateFromDevice(pose);
  71816. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71817. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71818. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71819. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71820. if (this._mesh) {
  71821. this._mesh.position.copyFrom(this.devicePosition);
  71822. if (this._mesh.rotationQuaternion) {
  71823. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71824. }
  71825. }
  71826. };
  71827. /**
  71828. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71829. * @param poseData raw pose fromthe device
  71830. */
  71831. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71832. if (poseData) {
  71833. this.rawPose = poseData;
  71834. if (poseData.position) {
  71835. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71836. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71837. this._deviceRoomPosition.z *= -1;
  71838. }
  71839. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71840. this._calculatedPosition.addInPlace(this.position);
  71841. }
  71842. var pose = this.rawPose;
  71843. if (poseData.orientation && pose.orientation) {
  71844. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71845. if (this._mesh) {
  71846. if (this._mesh.getScene().useRightHandedSystem) {
  71847. this._deviceRoomRotationQuaternion.z *= -1;
  71848. this._deviceRoomRotationQuaternion.w *= -1;
  71849. }
  71850. else {
  71851. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71852. }
  71853. }
  71854. // if the camera is set, rotate to the camera's rotation
  71855. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71856. }
  71857. }
  71858. };
  71859. /**
  71860. * Attaches a mesh to the controller
  71861. * @param mesh the mesh to be attached
  71862. */
  71863. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71864. if (this._mesh) {
  71865. this._mesh.parent = null;
  71866. }
  71867. this._mesh = mesh;
  71868. if (this._poseControlledCamera) {
  71869. this._mesh.parent = this._poseControlledCamera;
  71870. }
  71871. if (!this._mesh.rotationQuaternion) {
  71872. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71873. }
  71874. this._meshAttachedObservable.notifyObservers(mesh);
  71875. };
  71876. /**
  71877. * Attaches the controllers mesh to a camera
  71878. * @param camera the camera the mesh should be attached to
  71879. */
  71880. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71881. this._poseControlledCamera = camera;
  71882. if (this._mesh) {
  71883. this._mesh.parent = this._poseControlledCamera;
  71884. }
  71885. };
  71886. /**
  71887. * Disposes of the controller
  71888. */
  71889. PoseEnabledController.prototype.dispose = function () {
  71890. if (this._mesh) {
  71891. this._mesh.dispose();
  71892. }
  71893. this._mesh = null;
  71894. _super.prototype.dispose.call(this);
  71895. };
  71896. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71897. /**
  71898. * The mesh that is attached to the controller
  71899. */
  71900. get: function () {
  71901. return this._mesh;
  71902. },
  71903. enumerable: true,
  71904. configurable: true
  71905. });
  71906. /**
  71907. * Gets the ray of the controller in the direction the controller is pointing
  71908. * @param length the length the resulting ray should be
  71909. * @returns a ray in the direction the controller is pointing
  71910. */
  71911. PoseEnabledController.prototype.getForwardRay = function (length) {
  71912. if (length === void 0) { length = 100; }
  71913. if (!this.mesh) {
  71914. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71915. }
  71916. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71917. var origin = m.getTranslation();
  71918. var forward = new BABYLON.Vector3(0, 0, -1);
  71919. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71920. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71921. return new BABYLON.Ray(origin, direction, length);
  71922. };
  71923. /**
  71924. * Name of the child mesh that can be used to cast a ray from the controller
  71925. */
  71926. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71927. return PoseEnabledController;
  71928. }(BABYLON.Gamepad));
  71929. BABYLON.PoseEnabledController = PoseEnabledController;
  71930. })(BABYLON || (BABYLON = {}));
  71931. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71932. var BABYLON;
  71933. (function (BABYLON) {
  71934. /**
  71935. * Defines the WebVRController object that represents controllers tracked in 3D space
  71936. */
  71937. var WebVRController = /** @class */ (function (_super) {
  71938. __extends(WebVRController, _super);
  71939. /**
  71940. * Creates a new WebVRController from a gamepad
  71941. * @param vrGamepad the gamepad that the WebVRController should be created from
  71942. */
  71943. function WebVRController(vrGamepad) {
  71944. var _this = _super.call(this, vrGamepad) || this;
  71945. // Observables
  71946. /**
  71947. * Fired when the trigger state has changed
  71948. */
  71949. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71950. /**
  71951. * Fired when the main button state has changed
  71952. */
  71953. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71954. /**
  71955. * Fired when the secondary button state has changed
  71956. */
  71957. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71958. /**
  71959. * Fired when the pad state has changed
  71960. */
  71961. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71962. /**
  71963. * Fired when controllers stick values have changed
  71964. */
  71965. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71966. /**
  71967. * X and Y axis corrisponding to the controllers joystick
  71968. */
  71969. _this.pad = { x: 0, y: 0 };
  71970. // avoid GC, store state in a tmp object
  71971. _this._changes = {
  71972. pressChanged: false,
  71973. touchChanged: false,
  71974. valueChanged: false,
  71975. changed: false
  71976. };
  71977. _this._buttons = new Array(vrGamepad.buttons.length);
  71978. _this.hand = vrGamepad.hand;
  71979. return _this;
  71980. }
  71981. /**
  71982. * Fired when a controller button's state has changed
  71983. * @param callback the callback containing the button that was modified
  71984. */
  71985. WebVRController.prototype.onButtonStateChange = function (callback) {
  71986. this._onButtonStateChange = callback;
  71987. };
  71988. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71989. /**
  71990. * The default controller model for the controller
  71991. */
  71992. get: function () {
  71993. return this._defaultModel;
  71994. },
  71995. enumerable: true,
  71996. configurable: true
  71997. });
  71998. /**
  71999. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72000. */
  72001. WebVRController.prototype.update = function () {
  72002. _super.prototype.update.call(this);
  72003. for (var index = 0; index < this._buttons.length; index++) {
  72004. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72005. }
  72006. ;
  72007. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72008. this.pad.x = this.leftStick.x;
  72009. this.pad.y = this.leftStick.y;
  72010. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72011. }
  72012. };
  72013. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72014. if (!newState) {
  72015. newState = {
  72016. pressed: false,
  72017. touched: false,
  72018. value: 0
  72019. };
  72020. }
  72021. if (!currentState) {
  72022. this._buttons[buttonIndex] = {
  72023. pressed: newState.pressed,
  72024. touched: newState.touched,
  72025. value: newState.value
  72026. };
  72027. return;
  72028. }
  72029. this._checkChanges(newState, currentState);
  72030. if (this._changes.changed) {
  72031. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72032. this._handleButtonChange(buttonIndex, newState, this._changes);
  72033. }
  72034. this._buttons[buttonIndex].pressed = newState.pressed;
  72035. this._buttons[buttonIndex].touched = newState.touched;
  72036. // oculus triggers are never 0, thou not touched.
  72037. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72038. };
  72039. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72040. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72041. this._changes.touchChanged = newState.touched !== currentState.touched;
  72042. this._changes.valueChanged = newState.value !== currentState.value;
  72043. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72044. return this._changes;
  72045. };
  72046. /**
  72047. * Disposes of th webVRCOntroller
  72048. */
  72049. WebVRController.prototype.dispose = function () {
  72050. _super.prototype.dispose.call(this);
  72051. this.onTriggerStateChangedObservable.clear();
  72052. this.onMainButtonStateChangedObservable.clear();
  72053. this.onSecondaryButtonStateChangedObservable.clear();
  72054. this.onPadStateChangedObservable.clear();
  72055. this.onPadValuesChangedObservable.clear();
  72056. };
  72057. return WebVRController;
  72058. }(BABYLON.PoseEnabledController));
  72059. BABYLON.WebVRController = WebVRController;
  72060. })(BABYLON || (BABYLON = {}));
  72061. //# sourceMappingURL=babylon.webVRController.js.map
  72062. var BABYLON;
  72063. (function (BABYLON) {
  72064. /**
  72065. * Oculus Touch Controller
  72066. */
  72067. var OculusTouchController = /** @class */ (function (_super) {
  72068. __extends(OculusTouchController, _super);
  72069. /**
  72070. * Creates a new OculusTouchController from a gamepad
  72071. * @param vrGamepad the gamepad that the controller should be created from
  72072. */
  72073. function OculusTouchController(vrGamepad) {
  72074. var _this = _super.call(this, vrGamepad) || this;
  72075. /**
  72076. * Fired when the secondary trigger on this controller is modified
  72077. */
  72078. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72079. /**
  72080. * Fired when the thumb rest on this controller is modified
  72081. */
  72082. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72083. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72084. return _this;
  72085. }
  72086. /**
  72087. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72088. * @param scene scene in which to add meshes
  72089. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72090. */
  72091. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72092. var _this = this;
  72093. var meshName;
  72094. // Hand
  72095. if (this.hand === 'left') {
  72096. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72097. }
  72098. else { // Right is the default if no hand is specified
  72099. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72100. }
  72101. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72102. /*
  72103. Parent Mesh name: oculus_touch_left
  72104. - body
  72105. - trigger
  72106. - thumbstick
  72107. - grip
  72108. - button_y
  72109. - button_x
  72110. - button_enter
  72111. */
  72112. _this._defaultModel = newMeshes[1];
  72113. _this.attachToMesh(_this._defaultModel);
  72114. if (meshLoaded) {
  72115. meshLoaded(_this._defaultModel);
  72116. }
  72117. });
  72118. };
  72119. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72120. /**
  72121. * Fired when the A button on this controller is modified
  72122. */
  72123. get: function () {
  72124. if (this.hand === 'right') {
  72125. return this.onMainButtonStateChangedObservable;
  72126. }
  72127. else {
  72128. throw new Error('No A button on left hand');
  72129. }
  72130. },
  72131. enumerable: true,
  72132. configurable: true
  72133. });
  72134. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72135. /**
  72136. * Fired when the B button on this controller is modified
  72137. */
  72138. get: function () {
  72139. if (this.hand === 'right') {
  72140. return this.onSecondaryButtonStateChangedObservable;
  72141. }
  72142. else {
  72143. throw new Error('No B button on left hand');
  72144. }
  72145. },
  72146. enumerable: true,
  72147. configurable: true
  72148. });
  72149. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72150. /**
  72151. * Fired when the X button on this controller is modified
  72152. */
  72153. get: function () {
  72154. if (this.hand === 'left') {
  72155. return this.onMainButtonStateChangedObservable;
  72156. }
  72157. else {
  72158. throw new Error('No X button on right hand');
  72159. }
  72160. },
  72161. enumerable: true,
  72162. configurable: true
  72163. });
  72164. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72165. /**
  72166. * Fired when the Y button on this controller is modified
  72167. */
  72168. get: function () {
  72169. if (this.hand === 'left') {
  72170. return this.onSecondaryButtonStateChangedObservable;
  72171. }
  72172. else {
  72173. throw new Error('No Y button on right hand');
  72174. }
  72175. },
  72176. enumerable: true,
  72177. configurable: true
  72178. });
  72179. /**
  72180. * Called once for each button that changed state since the last frame
  72181. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72182. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72183. * 2) secondary trigger (same)
  72184. * 3) A (right) X (left), touch, pressed = value
  72185. * 4) B / Y
  72186. * 5) thumb rest
  72187. * @param buttonIdx Which button index changed
  72188. * @param state New state of the button
  72189. * @param changes Which properties on the state changed since last frame
  72190. */
  72191. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72192. var notifyObject = state; //{ state: state, changes: changes };
  72193. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72194. switch (buttonIdx) {
  72195. case 0:
  72196. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72197. return;
  72198. case 1: // index trigger
  72199. if (this._defaultModel) {
  72200. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72201. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72202. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72203. }
  72204. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72205. return;
  72206. case 2: // secondary trigger
  72207. if (this._defaultModel) {
  72208. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72209. }
  72210. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72211. return;
  72212. case 3:
  72213. if (this._defaultModel) {
  72214. if (notifyObject.pressed) {
  72215. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72216. }
  72217. else {
  72218. (this._defaultModel.getChildren()[1]).position.y = 0;
  72219. }
  72220. }
  72221. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72222. return;
  72223. case 4:
  72224. if (this._defaultModel) {
  72225. if (notifyObject.pressed) {
  72226. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72227. }
  72228. else {
  72229. (this._defaultModel.getChildren()[2]).position.y = 0;
  72230. }
  72231. }
  72232. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72233. return;
  72234. case 5:
  72235. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72236. return;
  72237. }
  72238. };
  72239. /**
  72240. * Base Url for the controller model.
  72241. */
  72242. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72243. /**
  72244. * File name for the left controller model.
  72245. */
  72246. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72247. /**
  72248. * File name for the right controller model.
  72249. */
  72250. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72251. return OculusTouchController;
  72252. }(BABYLON.WebVRController));
  72253. BABYLON.OculusTouchController = OculusTouchController;
  72254. })(BABYLON || (BABYLON = {}));
  72255. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72256. var BABYLON;
  72257. (function (BABYLON) {
  72258. /**
  72259. * Vive Controller
  72260. */
  72261. var ViveController = /** @class */ (function (_super) {
  72262. __extends(ViveController, _super);
  72263. /**
  72264. * Creates a new ViveController from a gamepad
  72265. * @param vrGamepad the gamepad that the controller should be created from
  72266. */
  72267. function ViveController(vrGamepad) {
  72268. var _this = _super.call(this, vrGamepad) || this;
  72269. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72270. _this._invertLeftStickY = true;
  72271. return _this;
  72272. }
  72273. /**
  72274. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72275. * @param scene scene in which to add meshes
  72276. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72277. */
  72278. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72279. var _this = this;
  72280. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72281. /*
  72282. Parent Mesh name: ViveWand
  72283. - body
  72284. - r_gripper
  72285. - l_gripper
  72286. - menu_button
  72287. - system_button
  72288. - trackpad
  72289. - trigger
  72290. - LED
  72291. */
  72292. _this._defaultModel = newMeshes[1];
  72293. _this.attachToMesh(_this._defaultModel);
  72294. if (meshLoaded) {
  72295. meshLoaded(_this._defaultModel);
  72296. }
  72297. });
  72298. };
  72299. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72300. /**
  72301. * Fired when the left button on this controller is modified
  72302. */
  72303. get: function () {
  72304. return this.onMainButtonStateChangedObservable;
  72305. },
  72306. enumerable: true,
  72307. configurable: true
  72308. });
  72309. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72310. /**
  72311. * Fired when the right button on this controller is modified
  72312. */
  72313. get: function () {
  72314. return this.onMainButtonStateChangedObservable;
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72320. /**
  72321. * Fired when the menu button on this controller is modified
  72322. */
  72323. get: function () {
  72324. return this.onSecondaryButtonStateChangedObservable;
  72325. },
  72326. enumerable: true,
  72327. configurable: true
  72328. });
  72329. /**
  72330. * Called once for each button that changed state since the last frame
  72331. * Vive mapping:
  72332. * 0: touchpad
  72333. * 1: trigger
  72334. * 2: left AND right buttons
  72335. * 3: menu button
  72336. * @param buttonIdx Which button index changed
  72337. * @param state New state of the button
  72338. * @param changes Which properties on the state changed since last frame
  72339. */
  72340. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72341. var notifyObject = state; //{ state: state, changes: changes };
  72342. switch (buttonIdx) {
  72343. case 0:
  72344. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72345. return;
  72346. case 1: // index trigger
  72347. if (this._defaultModel) {
  72348. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72349. }
  72350. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72351. return;
  72352. case 2: // left AND right button
  72353. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72354. return;
  72355. case 3:
  72356. if (this._defaultModel) {
  72357. if (notifyObject.pressed) {
  72358. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72359. }
  72360. else {
  72361. (this._defaultModel.getChildren()[2]).position.y = 0;
  72362. }
  72363. }
  72364. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72365. return;
  72366. }
  72367. };
  72368. /**
  72369. * Base Url for the controller model.
  72370. */
  72371. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72372. /**
  72373. * File name for the controller model.
  72374. */
  72375. ViveController.MODEL_FILENAME = 'wand.babylon';
  72376. return ViveController;
  72377. }(BABYLON.WebVRController));
  72378. BABYLON.ViveController = ViveController;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.viveController.js.map
  72381. var BABYLON;
  72382. (function (BABYLON) {
  72383. /**
  72384. * Generic Controller
  72385. */
  72386. var GenericController = /** @class */ (function (_super) {
  72387. __extends(GenericController, _super);
  72388. /**
  72389. * Creates a new GenericController from a gamepad
  72390. * @param vrGamepad the gamepad that the controller should be created from
  72391. */
  72392. function GenericController(vrGamepad) {
  72393. return _super.call(this, vrGamepad) || this;
  72394. }
  72395. /**
  72396. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72397. * @param scene scene in which to add meshes
  72398. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72399. */
  72400. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72401. var _this = this;
  72402. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72403. _this._defaultModel = newMeshes[1];
  72404. _this.attachToMesh(_this._defaultModel);
  72405. if (meshLoaded) {
  72406. meshLoaded(_this._defaultModel);
  72407. }
  72408. });
  72409. };
  72410. /**
  72411. * Called once for each button that changed state since the last frame
  72412. * @param buttonIdx Which button index changed
  72413. * @param state New state of the button
  72414. * @param changes Which properties on the state changed since last frame
  72415. */
  72416. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72417. console.log("Button id: " + buttonIdx + "state: ");
  72418. console.dir(state);
  72419. };
  72420. /**
  72421. * Base Url for the controller model.
  72422. */
  72423. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72424. /**
  72425. * File name for the controller model.
  72426. */
  72427. GenericController.MODEL_FILENAME = 'generic.babylon';
  72428. return GenericController;
  72429. }(BABYLON.WebVRController));
  72430. BABYLON.GenericController = GenericController;
  72431. })(BABYLON || (BABYLON = {}));
  72432. //# sourceMappingURL=babylon.genericController.js.map
  72433. var BABYLON;
  72434. (function (BABYLON) {
  72435. /**
  72436. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72437. */
  72438. var LoadedMeshInfo = /** @class */ (function () {
  72439. function LoadedMeshInfo() {
  72440. /**
  72441. * Map of the button meshes contained in the controller
  72442. */
  72443. this.buttonMeshes = {};
  72444. /**
  72445. * Map of the axis meshes contained in the controller
  72446. */
  72447. this.axisMeshes = {};
  72448. }
  72449. return LoadedMeshInfo;
  72450. }());
  72451. /**
  72452. * Defines the WindowsMotionController object that the state of the windows motion controller
  72453. */
  72454. var WindowsMotionController = /** @class */ (function (_super) {
  72455. __extends(WindowsMotionController, _super);
  72456. /**
  72457. * Creates a new WindowsMotionController from a gamepad
  72458. * @param vrGamepad the gamepad that the controller should be created from
  72459. */
  72460. function WindowsMotionController(vrGamepad) {
  72461. var _this = _super.call(this, vrGamepad) || this;
  72462. _this._mapping = {
  72463. // Semantic button names
  72464. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72465. // A mapping of the button name to glTF model node name
  72466. // that should be transformed by button value.
  72467. buttonMeshNames: {
  72468. 'trigger': 'SELECT',
  72469. 'menu': 'MENU',
  72470. 'grip': 'GRASP',
  72471. 'thumbstick': 'THUMBSTICK_PRESS',
  72472. 'trackpad': 'TOUCHPAD_PRESS'
  72473. },
  72474. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72475. buttonObservableNames: {
  72476. 'trigger': 'onTriggerStateChangedObservable',
  72477. 'menu': 'onSecondaryButtonStateChangedObservable',
  72478. 'grip': 'onMainButtonStateChangedObservable',
  72479. 'thumbstick': 'onPadStateChangedObservable',
  72480. 'trackpad': 'onTrackpadChangedObservable'
  72481. },
  72482. // A mapping of the axis name to glTF model node name
  72483. // that should be transformed by axis value.
  72484. // This array mirrors the browserGamepad.axes array, such that
  72485. // the mesh corresponding to axis 0 is in this array index 0.
  72486. axisMeshNames: [
  72487. 'THUMBSTICK_X',
  72488. 'THUMBSTICK_Y',
  72489. 'TOUCHPAD_TOUCH_X',
  72490. 'TOUCHPAD_TOUCH_Y'
  72491. ],
  72492. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72493. };
  72494. /**
  72495. * Fired when the trackpad on this controller is clicked
  72496. */
  72497. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72498. /**
  72499. * Fired when the trackpad on this controller is modified
  72500. */
  72501. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72502. /**
  72503. * The current x and y values of this controller's trackpad
  72504. */
  72505. _this.trackpad = { x: 0, y: 0 };
  72506. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72507. _this._loadedMeshInfo = null;
  72508. return _this;
  72509. }
  72510. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72511. /**
  72512. * Fired when the trigger on this controller is modified
  72513. */
  72514. get: function () {
  72515. return this.onTriggerStateChangedObservable;
  72516. },
  72517. enumerable: true,
  72518. configurable: true
  72519. });
  72520. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72521. /**
  72522. * Fired when the menu button on this controller is modified
  72523. */
  72524. get: function () {
  72525. return this.onSecondaryButtonStateChangedObservable;
  72526. },
  72527. enumerable: true,
  72528. configurable: true
  72529. });
  72530. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72531. /**
  72532. * Fired when the grip button on this controller is modified
  72533. */
  72534. get: function () {
  72535. return this.onMainButtonStateChangedObservable;
  72536. },
  72537. enumerable: true,
  72538. configurable: true
  72539. });
  72540. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72541. /**
  72542. * Fired when the thumbstick button on this controller is modified
  72543. */
  72544. get: function () {
  72545. return this.onPadStateChangedObservable;
  72546. },
  72547. enumerable: true,
  72548. configurable: true
  72549. });
  72550. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72551. /**
  72552. * Fired when the touchpad button on this controller is modified
  72553. */
  72554. get: function () {
  72555. return this.onTrackpadChangedObservable;
  72556. },
  72557. enumerable: true,
  72558. configurable: true
  72559. });
  72560. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72561. /**
  72562. * Fired when the touchpad values on this controller are modified
  72563. */
  72564. get: function () {
  72565. return this.onTrackpadValuesChangedObservable;
  72566. },
  72567. enumerable: true,
  72568. configurable: true
  72569. });
  72570. WindowsMotionController.prototype._updateTrackpad = function () {
  72571. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72572. this.trackpad.x = this.browserGamepad["axes"][2];
  72573. this.trackpad.y = this.browserGamepad["axes"][3];
  72574. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72575. }
  72576. };
  72577. /**
  72578. * Called once per frame by the engine.
  72579. */
  72580. WindowsMotionController.prototype.update = function () {
  72581. _super.prototype.update.call(this);
  72582. if (this.browserGamepad.axes) {
  72583. this._updateTrackpad();
  72584. // Only need to animate axes if there is a loaded mesh
  72585. if (this._loadedMeshInfo) {
  72586. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72587. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72588. }
  72589. }
  72590. }
  72591. };
  72592. /**
  72593. * Called once for each button that changed state since the last frame
  72594. * @param buttonIdx Which button index changed
  72595. * @param state New state of the button
  72596. * @param changes Which properties on the state changed since last frame
  72597. */
  72598. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72599. var buttonName = this._mapping.buttons[buttonIdx];
  72600. if (!buttonName) {
  72601. return;
  72602. }
  72603. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72604. this._updateTrackpad();
  72605. // Only emit events for buttons that we know how to map from index to name
  72606. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72607. if (observable) {
  72608. observable.notifyObservers(state);
  72609. }
  72610. this._lerpButtonTransform(buttonName, state.value);
  72611. };
  72612. /**
  72613. * Moves the buttons on the controller mesh based on their current state
  72614. * @param buttonName the name of the button to move
  72615. * @param buttonValue the value of the button which determines the buttons new position
  72616. */
  72617. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72618. // If there is no loaded mesh, there is nothing to transform.
  72619. if (!this._loadedMeshInfo) {
  72620. return;
  72621. }
  72622. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72623. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72624. return;
  72625. }
  72626. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72627. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72628. };
  72629. /**
  72630. * Moves the axis on the controller mesh based on its current state
  72631. * @param axis the index of the axis
  72632. * @param axisValue the value of the axis which determines the meshes new position
  72633. * @hidden
  72634. */
  72635. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72636. if (!this._loadedMeshInfo) {
  72637. return;
  72638. }
  72639. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72640. if (!meshInfo) {
  72641. return;
  72642. }
  72643. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72644. return;
  72645. }
  72646. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72647. var lerpValue = axisValue * 0.5 + 0.5;
  72648. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72649. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72650. };
  72651. /**
  72652. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72653. * @param scene scene in which to add meshes
  72654. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72655. */
  72656. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72657. var _this = this;
  72658. if (forceDefault === void 0) { forceDefault = false; }
  72659. var path;
  72660. var filename;
  72661. // Checking if GLB loader is present
  72662. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72663. // Determine the device specific folder based on the ID suffix
  72664. var device = 'default';
  72665. if (this.id && !forceDefault) {
  72666. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72667. device = ((match && match[0]) || device);
  72668. }
  72669. // Hand
  72670. if (this.hand === 'left') {
  72671. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72672. }
  72673. else { // Right is the default if no hand is specified
  72674. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72675. }
  72676. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72677. }
  72678. else {
  72679. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72680. path = BABYLON.GenericController.MODEL_BASE_URL;
  72681. filename = BABYLON.GenericController.MODEL_FILENAME;
  72682. }
  72683. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72684. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72685. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72686. if (!_this._loadedMeshInfo) {
  72687. return;
  72688. }
  72689. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72690. _this.attachToMesh(_this._defaultModel);
  72691. if (meshLoaded) {
  72692. meshLoaded(_this._defaultModel);
  72693. }
  72694. }, null, function (scene, message) {
  72695. BABYLON.Tools.Log(message);
  72696. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72697. if (!forceDefault) {
  72698. _this.initControllerMesh(scene, meshLoaded, true);
  72699. }
  72700. });
  72701. };
  72702. /**
  72703. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72704. * can be transformed by button presses and axes values, based on this._mapping.
  72705. *
  72706. * @param scene scene in which the meshes exist
  72707. * @param meshes list of meshes that make up the controller model to process
  72708. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72709. */
  72710. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72711. var loadedMeshInfo = null;
  72712. // Create a new mesh to contain the glTF hierarchy
  72713. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72714. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72715. var childMesh = null;
  72716. for (var i = 0; i < meshes.length; i++) {
  72717. var mesh = meshes[i];
  72718. if (!mesh.parent) {
  72719. // Exclude controller meshes from picking results
  72720. mesh.isPickable = false;
  72721. // Handle root node, attach to the new parentMesh
  72722. childMesh = mesh;
  72723. break;
  72724. }
  72725. }
  72726. if (childMesh) {
  72727. childMesh.setParent(parentMesh);
  72728. // Create our mesh info. Note that this method will always return non-null.
  72729. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72730. }
  72731. else {
  72732. BABYLON.Tools.Warn('Could not find root node in model file.');
  72733. }
  72734. return loadedMeshInfo;
  72735. };
  72736. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72737. var loadedMeshInfo = new LoadedMeshInfo();
  72738. var i;
  72739. loadedMeshInfo.rootNode = rootNode;
  72740. // Reset the caches
  72741. loadedMeshInfo.buttonMeshes = {};
  72742. loadedMeshInfo.axisMeshes = {};
  72743. // Button Meshes
  72744. for (i = 0; i < this._mapping.buttons.length; i++) {
  72745. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72746. if (!buttonMeshName) {
  72747. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72748. continue;
  72749. }
  72750. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72751. if (!buttonMesh) {
  72752. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72753. continue;
  72754. }
  72755. var buttonMeshInfo = {
  72756. index: i,
  72757. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72758. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72759. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72760. };
  72761. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72762. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72763. }
  72764. else {
  72765. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72766. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72767. '(VALUE: ' + !!buttonMeshInfo.value +
  72768. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72769. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72770. ')');
  72771. }
  72772. }
  72773. // Axis Meshes
  72774. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72775. var axisMeshName = this._mapping.axisMeshNames[i];
  72776. if (!axisMeshName) {
  72777. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72778. continue;
  72779. }
  72780. var axisMesh = getChildByName(rootNode, axisMeshName);
  72781. if (!axisMesh) {
  72782. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72783. continue;
  72784. }
  72785. var axisMeshInfo = {
  72786. index: i,
  72787. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72788. min: getImmediateChildByName(axisMesh, 'MIN'),
  72789. max: getImmediateChildByName(axisMesh, 'MAX')
  72790. };
  72791. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72792. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72793. }
  72794. else {
  72795. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72796. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72797. '(VALUE: ' + !!axisMeshInfo.value +
  72798. ', MIN: ' + !!axisMeshInfo.min +
  72799. ', MAX:' + !!axisMeshInfo.max +
  72800. ')');
  72801. }
  72802. }
  72803. // Pointing Ray
  72804. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72805. if (!loadedMeshInfo.pointingPoseNode) {
  72806. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72807. }
  72808. return loadedMeshInfo;
  72809. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72810. function getChildByName(node, name) {
  72811. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72812. }
  72813. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72814. function getImmediateChildByName(node, name) {
  72815. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72816. }
  72817. };
  72818. /**
  72819. * Gets the ray of the controller in the direction the controller is pointing
  72820. * @param length the length the resulting ray should be
  72821. * @returns a ray in the direction the controller is pointing
  72822. */
  72823. WindowsMotionController.prototype.getForwardRay = function (length) {
  72824. if (length === void 0) { length = 100; }
  72825. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72826. return _super.prototype.getForwardRay.call(this, length);
  72827. }
  72828. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72829. var origin = m.getTranslation();
  72830. var forward = new BABYLON.Vector3(0, 0, -1);
  72831. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72832. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72833. return new BABYLON.Ray(origin, direction, length);
  72834. };
  72835. /**
  72836. * Disposes of the controller
  72837. */
  72838. WindowsMotionController.prototype.dispose = function () {
  72839. _super.prototype.dispose.call(this);
  72840. this.onTrackpadChangedObservable.clear();
  72841. };
  72842. /**
  72843. * The base url used to load the left and right controller models
  72844. */
  72845. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72846. /**
  72847. * The name of the left controller model file
  72848. */
  72849. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72850. /**
  72851. * The name of the right controller model file
  72852. */
  72853. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72854. /**
  72855. * The controller name prefix for this controller type
  72856. */
  72857. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72858. /**
  72859. * The controller id pattern for this controller type
  72860. */
  72861. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72862. return WindowsMotionController;
  72863. }(BABYLON.WebVRController));
  72864. BABYLON.WindowsMotionController = WindowsMotionController;
  72865. })(BABYLON || (BABYLON = {}));
  72866. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72867. var BABYLON;
  72868. (function (BABYLON) {
  72869. /**
  72870. * Gear VR Controller
  72871. */
  72872. var GearVRController = /** @class */ (function (_super) {
  72873. __extends(GearVRController, _super);
  72874. /**
  72875. * Creates a new GearVRController from a gamepad
  72876. * @param vrGamepad the gamepad that the controller should be created from
  72877. */
  72878. function GearVRController(vrGamepad) {
  72879. var _this = _super.call(this, vrGamepad) || this;
  72880. _this._buttonIndexToObservableNameMap = [
  72881. 'onTrackpadChangedObservable',
  72882. 'onTriggerStateChangedObservable' // Trigger
  72883. ];
  72884. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72885. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72886. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72887. return _this;
  72888. }
  72889. /**
  72890. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72891. * @param scene scene in which to add meshes
  72892. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72893. */
  72894. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72895. var _this = this;
  72896. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72897. _this._defaultModel = newMeshes[1];
  72898. _this.attachToMesh(_this._defaultModel);
  72899. if (meshLoaded) {
  72900. meshLoaded(_this._defaultModel);
  72901. }
  72902. });
  72903. };
  72904. /**
  72905. * Called once for each button that changed state since the last frame
  72906. * @param buttonIdx Which button index changed
  72907. * @param state New state of the button
  72908. * @param changes Which properties on the state changed since last frame
  72909. */
  72910. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72911. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72912. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72913. // Only emit events for buttons that we know how to map from index to observable
  72914. var observable = this[observableName];
  72915. if (observable) {
  72916. observable.notifyObservers(state);
  72917. }
  72918. }
  72919. };
  72920. /**
  72921. * Base Url for the controller model.
  72922. */
  72923. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72924. /**
  72925. * File name for the controller model.
  72926. */
  72927. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72928. /**
  72929. * Gamepad Id prefix used to identify this controller.
  72930. */
  72931. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72932. return GearVRController;
  72933. }(BABYLON.WebVRController));
  72934. BABYLON.GearVRController = GearVRController;
  72935. })(BABYLON || (BABYLON = {}));
  72936. //# sourceMappingURL=babylon.gearVRController.js.map
  72937. var BABYLON;
  72938. (function (BABYLON) {
  72939. /**
  72940. * Google Daydream controller
  72941. */
  72942. var DaydreamController = /** @class */ (function (_super) {
  72943. __extends(DaydreamController, _super);
  72944. /**
  72945. * Creates a new DaydreamController from a gamepad
  72946. * @param vrGamepad the gamepad that the controller should be created from
  72947. */
  72948. function DaydreamController(vrGamepad) {
  72949. var _this = _super.call(this, vrGamepad) || this;
  72950. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72951. return _this;
  72952. }
  72953. /**
  72954. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72955. * @param scene scene in which to add meshes
  72956. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72957. */
  72958. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72959. var _this = this;
  72960. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72961. _this._defaultModel = newMeshes[1];
  72962. _this.attachToMesh(_this._defaultModel);
  72963. if (meshLoaded) {
  72964. meshLoaded(_this._defaultModel);
  72965. }
  72966. });
  72967. };
  72968. /**
  72969. * Called once for each button that changed state since the last frame
  72970. * @param buttonIdx Which button index changed
  72971. * @param state New state of the button
  72972. * @param changes Which properties on the state changed since last frame
  72973. */
  72974. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72975. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72976. if (buttonIdx === 0) {
  72977. var observable = this.onTriggerStateChangedObservable;
  72978. if (observable) {
  72979. observable.notifyObservers(state);
  72980. }
  72981. }
  72982. else {
  72983. // If the app or home buttons are ever made available
  72984. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72985. }
  72986. };
  72987. /**
  72988. * Base Url for the controller model.
  72989. */
  72990. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72991. /**
  72992. * File name for the controller model.
  72993. */
  72994. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72995. /**
  72996. * Gamepad Id prefix used to identify Daydream Controller.
  72997. */
  72998. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72999. return DaydreamController;
  73000. }(BABYLON.WebVRController));
  73001. BABYLON.DaydreamController = DaydreamController;
  73002. })(BABYLON || (BABYLON = {}));
  73003. //# sourceMappingURL=babylon.daydreamController.js.map
  73004. var BABYLON;
  73005. (function (BABYLON) {
  73006. var FollowCamera = /** @class */ (function (_super) {
  73007. __extends(FollowCamera, _super);
  73008. function FollowCamera(name, position, scene, lockedTarget) {
  73009. if (lockedTarget === void 0) { lockedTarget = null; }
  73010. var _this = _super.call(this, name, position, scene) || this;
  73011. _this.radius = 12;
  73012. _this.rotationOffset = 0;
  73013. _this.heightOffset = 4;
  73014. _this.cameraAcceleration = 0.05;
  73015. _this.maxCameraSpeed = 20;
  73016. _this.lockedTarget = lockedTarget;
  73017. return _this;
  73018. }
  73019. FollowCamera.prototype.getRadians = function (degrees) {
  73020. return degrees * Math.PI / 180;
  73021. };
  73022. FollowCamera.prototype.follow = function (cameraTarget) {
  73023. if (!cameraTarget)
  73024. return;
  73025. var yRotation;
  73026. if (cameraTarget.rotationQuaternion) {
  73027. var rotMatrix = new BABYLON.Matrix();
  73028. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73029. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73030. }
  73031. else {
  73032. yRotation = cameraTarget.rotation.y;
  73033. }
  73034. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73035. var targetPosition = cameraTarget.getAbsolutePosition();
  73036. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73037. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73038. var dx = targetX - this.position.x;
  73039. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73040. var dz = (targetZ) - this.position.z;
  73041. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73042. var vy = dy * this.cameraAcceleration;
  73043. var vz = dz * this.cameraAcceleration * 2;
  73044. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73045. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73046. }
  73047. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73048. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73049. }
  73050. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73051. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73052. }
  73053. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73054. this.setTarget(targetPosition);
  73055. };
  73056. FollowCamera.prototype._checkInputs = function () {
  73057. _super.prototype._checkInputs.call(this);
  73058. if (this.lockedTarget) {
  73059. this.follow(this.lockedTarget);
  73060. }
  73061. };
  73062. FollowCamera.prototype.getClassName = function () {
  73063. return "FollowCamera";
  73064. };
  73065. __decorate([
  73066. BABYLON.serialize()
  73067. ], FollowCamera.prototype, "radius", void 0);
  73068. __decorate([
  73069. BABYLON.serialize()
  73070. ], FollowCamera.prototype, "rotationOffset", void 0);
  73071. __decorate([
  73072. BABYLON.serialize()
  73073. ], FollowCamera.prototype, "heightOffset", void 0);
  73074. __decorate([
  73075. BABYLON.serialize()
  73076. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73077. __decorate([
  73078. BABYLON.serialize()
  73079. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73080. __decorate([
  73081. BABYLON.serializeAsMeshReference("lockedTargetId")
  73082. ], FollowCamera.prototype, "lockedTarget", void 0);
  73083. return FollowCamera;
  73084. }(BABYLON.TargetCamera));
  73085. BABYLON.FollowCamera = FollowCamera;
  73086. var ArcFollowCamera = /** @class */ (function (_super) {
  73087. __extends(ArcFollowCamera, _super);
  73088. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73089. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73090. _this.alpha = alpha;
  73091. _this.beta = beta;
  73092. _this.radius = radius;
  73093. _this.target = target;
  73094. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73095. _this.follow();
  73096. return _this;
  73097. }
  73098. ArcFollowCamera.prototype.follow = function () {
  73099. if (!this.target) {
  73100. return;
  73101. }
  73102. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73103. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73104. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73105. var targetPosition = this.target.getAbsolutePosition();
  73106. this.position = targetPosition.add(this._cartesianCoordinates);
  73107. this.setTarget(targetPosition);
  73108. };
  73109. ArcFollowCamera.prototype._checkInputs = function () {
  73110. _super.prototype._checkInputs.call(this);
  73111. this.follow();
  73112. };
  73113. ArcFollowCamera.prototype.getClassName = function () {
  73114. return "ArcFollowCamera";
  73115. };
  73116. return ArcFollowCamera;
  73117. }(BABYLON.TargetCamera));
  73118. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73119. })(BABYLON || (BABYLON = {}));
  73120. //# sourceMappingURL=babylon.followCamera.js.map
  73121. var BABYLON;
  73122. (function (BABYLON) {
  73123. // We're mainly based on the logic defined into the FreeCamera code
  73124. var UniversalCamera = /** @class */ (function (_super) {
  73125. __extends(UniversalCamera, _super);
  73126. //-- end properties for backward compatibility for inputs
  73127. function UniversalCamera(name, position, scene) {
  73128. var _this = _super.call(this, name, position, scene) || this;
  73129. _this.inputs.addGamepad();
  73130. return _this;
  73131. }
  73132. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73133. //-- Begin properties for backward compatibility for inputs
  73134. get: function () {
  73135. var gamepad = this.inputs.attached["gamepad"];
  73136. if (gamepad)
  73137. return gamepad.gamepadAngularSensibility;
  73138. return 0;
  73139. },
  73140. set: function (value) {
  73141. var gamepad = this.inputs.attached["gamepad"];
  73142. if (gamepad)
  73143. gamepad.gamepadAngularSensibility = value;
  73144. },
  73145. enumerable: true,
  73146. configurable: true
  73147. });
  73148. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73149. get: function () {
  73150. var gamepad = this.inputs.attached["gamepad"];
  73151. if (gamepad)
  73152. return gamepad.gamepadMoveSensibility;
  73153. return 0;
  73154. },
  73155. set: function (value) {
  73156. var gamepad = this.inputs.attached["gamepad"];
  73157. if (gamepad)
  73158. gamepad.gamepadMoveSensibility = value;
  73159. },
  73160. enumerable: true,
  73161. configurable: true
  73162. });
  73163. UniversalCamera.prototype.getClassName = function () {
  73164. return "UniversalCamera";
  73165. };
  73166. return UniversalCamera;
  73167. }(BABYLON.TouchCamera));
  73168. BABYLON.UniversalCamera = UniversalCamera;
  73169. })(BABYLON || (BABYLON = {}));
  73170. //# sourceMappingURL=babylon.universalCamera.js.map
  73171. var BABYLON;
  73172. (function (BABYLON) {
  73173. // We're mainly based on the logic defined into the FreeCamera code
  73174. var GamepadCamera = /** @class */ (function (_super) {
  73175. __extends(GamepadCamera, _super);
  73176. //-- end properties for backward compatibility for inputs
  73177. function GamepadCamera(name, position, scene) {
  73178. return _super.call(this, name, position, scene) || this;
  73179. }
  73180. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73181. //-- Begin properties for backward compatibility for inputs
  73182. get: function () {
  73183. var gamepad = this.inputs.attached["gamepad"];
  73184. if (gamepad)
  73185. return gamepad.gamepadAngularSensibility;
  73186. return 0;
  73187. },
  73188. set: function (value) {
  73189. var gamepad = this.inputs.attached["gamepad"];
  73190. if (gamepad)
  73191. gamepad.gamepadAngularSensibility = value;
  73192. },
  73193. enumerable: true,
  73194. configurable: true
  73195. });
  73196. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73197. get: function () {
  73198. var gamepad = this.inputs.attached["gamepad"];
  73199. if (gamepad)
  73200. return gamepad.gamepadMoveSensibility;
  73201. return 0;
  73202. },
  73203. set: function (value) {
  73204. var gamepad = this.inputs.attached["gamepad"];
  73205. if (gamepad)
  73206. gamepad.gamepadMoveSensibility = value;
  73207. },
  73208. enumerable: true,
  73209. configurable: true
  73210. });
  73211. GamepadCamera.prototype.getClassName = function () {
  73212. return "GamepadCamera";
  73213. };
  73214. return GamepadCamera;
  73215. }(BABYLON.UniversalCamera));
  73216. BABYLON.GamepadCamera = GamepadCamera;
  73217. })(BABYLON || (BABYLON = {}));
  73218. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73219. var BABYLON;
  73220. (function (BABYLON) {
  73221. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73222. function PostProcessRenderPipelineManager() {
  73223. this._renderPipelines = {};
  73224. }
  73225. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73226. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73227. };
  73228. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73229. if (unique === void 0) { unique = false; }
  73230. var renderPipeline = this._renderPipelines[renderPipelineName];
  73231. if (!renderPipeline) {
  73232. return;
  73233. }
  73234. renderPipeline._attachCameras(cameras, unique);
  73235. };
  73236. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73237. var renderPipeline = this._renderPipelines[renderPipelineName];
  73238. if (!renderPipeline) {
  73239. return;
  73240. }
  73241. renderPipeline._detachCameras(cameras);
  73242. };
  73243. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73244. var renderPipeline = this._renderPipelines[renderPipelineName];
  73245. if (!renderPipeline) {
  73246. return;
  73247. }
  73248. renderPipeline._enableEffect(renderEffectName, cameras);
  73249. };
  73250. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73251. var renderPipeline = this._renderPipelines[renderPipelineName];
  73252. if (!renderPipeline) {
  73253. return;
  73254. }
  73255. renderPipeline._disableEffect(renderEffectName, cameras);
  73256. };
  73257. PostProcessRenderPipelineManager.prototype.update = function () {
  73258. for (var renderPipelineName in this._renderPipelines) {
  73259. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73260. var pipeline = this._renderPipelines[renderPipelineName];
  73261. if (!pipeline.isSupported) {
  73262. pipeline.dispose();
  73263. delete this._renderPipelines[renderPipelineName];
  73264. }
  73265. else {
  73266. pipeline._update();
  73267. }
  73268. }
  73269. }
  73270. };
  73271. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73272. for (var renderPipelineName in this._renderPipelines) {
  73273. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73274. var pipeline = this._renderPipelines[renderPipelineName];
  73275. pipeline._rebuild();
  73276. }
  73277. }
  73278. };
  73279. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73280. for (var renderPipelineName in this._renderPipelines) {
  73281. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73282. var pipeline = this._renderPipelines[renderPipelineName];
  73283. pipeline.dispose();
  73284. }
  73285. }
  73286. };
  73287. return PostProcessRenderPipelineManager;
  73288. }());
  73289. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73290. })(BABYLON || (BABYLON = {}));
  73291. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73292. var BABYLON;
  73293. (function (BABYLON) {
  73294. /**
  73295. * This represents a set of one or more post processes in Babylon.
  73296. * A post process can be used to apply a shader to a texture after it is rendered.
  73297. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73298. */
  73299. var PostProcessRenderEffect = /** @class */ (function () {
  73300. /**
  73301. * Instantiates a post process render effect.
  73302. * A post process can be used to apply a shader to a texture after it is rendered.
  73303. * @param engine The engine the effect is tied to
  73304. * @param name The name of the effect
  73305. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73306. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73307. */
  73308. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73309. this._name = name;
  73310. this._singleInstance = singleInstance || true;
  73311. this._getPostProcesses = getPostProcesses;
  73312. this._cameras = {};
  73313. this._indicesForCamera = {};
  73314. this._postProcesses = {};
  73315. }
  73316. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73317. /**
  73318. * Checks if all the post processes in the effect are supported.
  73319. */
  73320. get: function () {
  73321. for (var index in this._postProcesses) {
  73322. if (this._postProcesses.hasOwnProperty(index)) {
  73323. var pps = this._postProcesses[index];
  73324. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73325. if (!pps[ppIndex].isSupported) {
  73326. return false;
  73327. }
  73328. }
  73329. }
  73330. }
  73331. return true;
  73332. },
  73333. enumerable: true,
  73334. configurable: true
  73335. });
  73336. /**
  73337. * Updates the current state of the effect
  73338. */
  73339. PostProcessRenderEffect.prototype._update = function () {
  73340. };
  73341. /**
  73342. * Attaches the effect on cameras
  73343. * @param cameras The camera to attach to.
  73344. */
  73345. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73346. var _this = this;
  73347. var cameraKey;
  73348. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73349. if (!cams) {
  73350. return;
  73351. }
  73352. for (var i = 0; i < cams.length; i++) {
  73353. var camera = cams[i];
  73354. var cameraName = camera.name;
  73355. if (this._singleInstance) {
  73356. cameraKey = 0;
  73357. }
  73358. else {
  73359. cameraKey = cameraName;
  73360. }
  73361. if (!this._postProcesses[cameraKey]) {
  73362. var postProcess = this._getPostProcesses();
  73363. if (postProcess) {
  73364. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73365. }
  73366. }
  73367. if (!this._indicesForCamera[cameraName]) {
  73368. this._indicesForCamera[cameraName] = [];
  73369. }
  73370. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73371. var index = camera.attachPostProcess(postProcess);
  73372. _this._indicesForCamera[cameraName].push(index);
  73373. });
  73374. if (!this._cameras[cameraName]) {
  73375. this._cameras[cameraName] = camera;
  73376. }
  73377. }
  73378. };
  73379. /**
  73380. * Detatches the effect on cameras
  73381. * @param cameras The camera to detatch from.
  73382. */
  73383. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73384. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73385. if (!cams) {
  73386. return;
  73387. }
  73388. for (var i = 0; i < cams.length; i++) {
  73389. var camera = cams[i];
  73390. var cameraName = camera.name;
  73391. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73392. camera.detachPostProcess(postProcess);
  73393. });
  73394. if (this._cameras[cameraName]) {
  73395. //this._indicesForCamera.splice(index, 1);
  73396. this._cameras[cameraName] = null;
  73397. }
  73398. }
  73399. };
  73400. /**
  73401. * Enables the effect on given cameras
  73402. * @param cameras The camera to enable.
  73403. */
  73404. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73405. var _this = this;
  73406. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73407. if (!cams) {
  73408. return;
  73409. }
  73410. for (var i = 0; i < cams.length; i++) {
  73411. var camera = cams[i];
  73412. var cameraName = camera.name;
  73413. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73414. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73415. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73416. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73417. });
  73418. }
  73419. }
  73420. }
  73421. };
  73422. /**
  73423. * Disables the effect on the given cameras
  73424. * @param cameras The camera to disable.
  73425. */
  73426. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73427. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73428. if (!cams) {
  73429. return;
  73430. }
  73431. for (var i = 0; i < cams.length; i++) {
  73432. var camera = cams[i];
  73433. var cameraName = camera.name;
  73434. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73435. camera.detachPostProcess(postProcess);
  73436. });
  73437. }
  73438. };
  73439. /**
  73440. * Gets a list of the post processes contained in the effect.
  73441. * @param camera The camera to get the post processes on.
  73442. * @returns The list of the post processes in the effect.
  73443. */
  73444. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73445. if (this._singleInstance) {
  73446. return this._postProcesses[0];
  73447. }
  73448. else {
  73449. if (!camera) {
  73450. return null;
  73451. }
  73452. return this._postProcesses[camera.name];
  73453. }
  73454. };
  73455. return PostProcessRenderEffect;
  73456. }());
  73457. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73458. })(BABYLON || (BABYLON = {}));
  73459. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73460. var BABYLON;
  73461. (function (BABYLON) {
  73462. var PostProcessRenderPipeline = /** @class */ (function () {
  73463. function PostProcessRenderPipeline(engine, name) {
  73464. this.engine = engine;
  73465. this._name = name;
  73466. this._renderEffects = {};
  73467. this._renderEffectsForIsolatedPass = new Array();
  73468. this._cameras = [];
  73469. }
  73470. PostProcessRenderPipeline.prototype.getClassName = function () {
  73471. return "PostProcessRenderPipeline";
  73472. };
  73473. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73474. get: function () {
  73475. for (var renderEffectName in this._renderEffects) {
  73476. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73477. if (!this._renderEffects[renderEffectName].isSupported) {
  73478. return false;
  73479. }
  73480. }
  73481. }
  73482. return true;
  73483. },
  73484. enumerable: true,
  73485. configurable: true
  73486. });
  73487. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73488. this._renderEffects[renderEffect._name] = renderEffect;
  73489. };
  73490. // private
  73491. PostProcessRenderPipeline.prototype._rebuild = function () {
  73492. };
  73493. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73494. var renderEffects = this._renderEffects[renderEffectName];
  73495. if (!renderEffects) {
  73496. return;
  73497. }
  73498. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73499. };
  73500. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73501. var renderEffects = this._renderEffects[renderEffectName];
  73502. if (!renderEffects) {
  73503. return;
  73504. }
  73505. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73506. };
  73507. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73508. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73509. if (!cams) {
  73510. return;
  73511. }
  73512. var indicesToDelete = [];
  73513. var i;
  73514. for (i = 0; i < cams.length; i++) {
  73515. var camera = cams[i];
  73516. var cameraName = camera.name;
  73517. if (this._cameras.indexOf(camera) === -1) {
  73518. this._cameras[cameraName] = camera;
  73519. }
  73520. else if (unique) {
  73521. indicesToDelete.push(i);
  73522. }
  73523. }
  73524. for (i = 0; i < indicesToDelete.length; i++) {
  73525. cameras.splice(indicesToDelete[i], 1);
  73526. }
  73527. for (var renderEffectName in this._renderEffects) {
  73528. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73529. this._renderEffects[renderEffectName]._attachCameras(cams);
  73530. }
  73531. }
  73532. };
  73533. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73534. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73535. if (!cams) {
  73536. return;
  73537. }
  73538. for (var renderEffectName in this._renderEffects) {
  73539. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73540. this._renderEffects[renderEffectName]._detachCameras(cams);
  73541. }
  73542. }
  73543. for (var i = 0; i < cams.length; i++) {
  73544. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73545. }
  73546. };
  73547. PostProcessRenderPipeline.prototype._update = function () {
  73548. for (var renderEffectName in this._renderEffects) {
  73549. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73550. this._renderEffects[renderEffectName]._update();
  73551. }
  73552. }
  73553. for (var i = 0; i < this._cameras.length; i++) {
  73554. var cameraName = this._cameras[i].name;
  73555. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73556. this._renderEffectsForIsolatedPass[cameraName]._update();
  73557. }
  73558. }
  73559. };
  73560. PostProcessRenderPipeline.prototype._reset = function () {
  73561. this._renderEffects = {};
  73562. this._renderEffectsForIsolatedPass = new Array();
  73563. };
  73564. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73565. // 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)
  73566. var effectKeys = Object.keys(this._renderEffects);
  73567. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73568. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73569. if (postProcesses) {
  73570. postProcesses[0].samples = sampleCount;
  73571. return true;
  73572. }
  73573. }
  73574. return false;
  73575. };
  73576. PostProcessRenderPipeline.prototype.dispose = function () {
  73577. // Must be implemented by children
  73578. };
  73579. __decorate([
  73580. BABYLON.serialize()
  73581. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73582. return PostProcessRenderPipeline;
  73583. }());
  73584. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73585. })(BABYLON || (BABYLON = {}));
  73586. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73587. var BABYLON;
  73588. (function (BABYLON) {
  73589. /**
  73590. * This represents a depth renderer in Babylon.
  73591. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73592. */
  73593. var DepthRenderer = /** @class */ (function () {
  73594. /**
  73595. * Instantiates a depth renderer
  73596. * @param scene The scene the renderer belongs to
  73597. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73598. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73599. */
  73600. function DepthRenderer(scene, type, camera) {
  73601. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73602. if (camera === void 0) { camera = null; }
  73603. var _this = this;
  73604. this._scene = scene;
  73605. this._camera = camera;
  73606. var engine = scene.getEngine();
  73607. // Render target
  73608. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73609. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73610. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73611. this._depthMap.refreshRate = 1;
  73612. this._depthMap.renderParticles = false;
  73613. this._depthMap.renderList = null;
  73614. // Camera to get depth map from to support multiple concurrent cameras
  73615. this._depthMap.activeCamera = this._camera;
  73616. this._depthMap.ignoreCameraViewport = true;
  73617. this._depthMap.useCameraPostProcesses = false;
  73618. // set default depth value to 1.0 (far away)
  73619. this._depthMap.onClearObservable.add(function (engine) {
  73620. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73621. });
  73622. // Custom render function
  73623. var renderSubMesh = function (subMesh) {
  73624. var mesh = subMesh.getRenderingMesh();
  73625. var scene = _this._scene;
  73626. var engine = scene.getEngine();
  73627. var material = subMesh.getMaterial();
  73628. if (!material) {
  73629. return;
  73630. }
  73631. // Culling and reverse (right handed system)
  73632. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73633. // Managing instances
  73634. var batch = mesh._getInstancesRenderList(subMesh._id);
  73635. if (batch.mustReturn) {
  73636. return;
  73637. }
  73638. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73639. var camera = _this._camera || scene.activeCamera;
  73640. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73641. engine.enableEffect(_this._effect);
  73642. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73643. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73644. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73645. // Alpha test
  73646. if (material && material.needAlphaTesting()) {
  73647. var alphaTexture = material.getAlphaTestTexture();
  73648. if (alphaTexture) {
  73649. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73650. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73651. }
  73652. }
  73653. // Bones
  73654. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73655. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73656. }
  73657. // Draw
  73658. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73659. }
  73660. };
  73661. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73662. var index;
  73663. if (depthOnlySubMeshes.length) {
  73664. engine.setColorWrite(false);
  73665. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73666. renderSubMesh(depthOnlySubMeshes.data[index]);
  73667. }
  73668. engine.setColorWrite(true);
  73669. }
  73670. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73671. renderSubMesh(opaqueSubMeshes.data[index]);
  73672. }
  73673. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73674. renderSubMesh(alphaTestSubMeshes.data[index]);
  73675. }
  73676. };
  73677. }
  73678. /**
  73679. * Creates the depth rendering effect and checks if the effect is ready.
  73680. * @param subMesh The submesh to be used to render the depth map of
  73681. * @param useInstances If multiple world instances should be used
  73682. * @returns if the depth renderer is ready to render the depth map
  73683. */
  73684. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73685. var material = subMesh.getMaterial();
  73686. if (material.disableDepthWrite) {
  73687. return false;
  73688. }
  73689. var defines = [];
  73690. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73691. var mesh = subMesh.getMesh();
  73692. // Alpha test
  73693. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73694. defines.push("#define ALPHATEST");
  73695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73696. attribs.push(BABYLON.VertexBuffer.UVKind);
  73697. defines.push("#define UV1");
  73698. }
  73699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73700. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73701. defines.push("#define UV2");
  73702. }
  73703. }
  73704. // Bones
  73705. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73708. if (mesh.numBoneInfluencers > 4) {
  73709. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73710. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73711. }
  73712. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73713. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73714. }
  73715. else {
  73716. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73717. }
  73718. // Instances
  73719. if (useInstances) {
  73720. defines.push("#define INSTANCES");
  73721. attribs.push("world0");
  73722. attribs.push("world1");
  73723. attribs.push("world2");
  73724. attribs.push("world3");
  73725. }
  73726. // Get correct effect
  73727. var join = defines.join("\n");
  73728. if (this._cachedDefines !== join) {
  73729. this._cachedDefines = join;
  73730. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73731. }
  73732. return this._effect.isReady();
  73733. };
  73734. /**
  73735. * Gets the texture which the depth map will be written to.
  73736. * @returns The depth map texture
  73737. */
  73738. DepthRenderer.prototype.getDepthMap = function () {
  73739. return this._depthMap;
  73740. };
  73741. /**
  73742. * Disposes of the depth renderer.
  73743. */
  73744. DepthRenderer.prototype.dispose = function () {
  73745. this._depthMap.dispose();
  73746. };
  73747. return DepthRenderer;
  73748. }());
  73749. BABYLON.DepthRenderer = DepthRenderer;
  73750. })(BABYLON || (BABYLON = {}));
  73751. //# sourceMappingURL=babylon.depthRenderer.js.map
  73752. var BABYLON;
  73753. (function (BABYLON) {
  73754. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73755. __extends(SSAORenderingPipeline, _super);
  73756. /**
  73757. * @constructor
  73758. * @param {string} name - The rendering pipeline name
  73759. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73760. * @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 }
  73761. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73762. */
  73763. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73764. var _this = _super.call(this, scene.getEngine(), name) || this;
  73765. // Members
  73766. /**
  73767. * The PassPostProcess id in the pipeline that contains the original scene color
  73768. */
  73769. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73770. /**
  73771. * The SSAO PostProcess id in the pipeline
  73772. */
  73773. _this.SSAORenderEffect = "SSAORenderEffect";
  73774. /**
  73775. * The horizontal blur PostProcess id in the pipeline
  73776. */
  73777. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73778. /**
  73779. * The vertical blur PostProcess id in the pipeline
  73780. */
  73781. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73782. /**
  73783. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73784. */
  73785. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73786. /**
  73787. * The output strength of the SSAO post-process. Default value is 1.0.
  73788. */
  73789. _this.totalStrength = 1.0;
  73790. /**
  73791. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73792. */
  73793. _this.radius = 0.0001;
  73794. /**
  73795. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73796. * Must not be equal to fallOff and superior to fallOff.
  73797. * Default value is 0.975
  73798. */
  73799. _this.area = 0.0075;
  73800. /**
  73801. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73802. * Must not be equal to area and inferior to area.
  73803. * Default value is 0.0
  73804. */
  73805. _this.fallOff = 0.000001;
  73806. /**
  73807. * The base color of the SSAO post-process
  73808. * The final result is "base + ssao" between [0, 1]
  73809. */
  73810. _this.base = 0.5;
  73811. _this._firstUpdate = true;
  73812. _this._scene = scene;
  73813. // Set up assets
  73814. _this._createRandomTexture();
  73815. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73816. var ssaoRatio = ratio.ssaoRatio || ratio;
  73817. var combineRatio = ratio.combineRatio || ratio;
  73818. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73819. _this._createSSAOPostProcess(ssaoRatio);
  73820. _this._createBlurPostProcess(ssaoRatio);
  73821. _this._createSSAOCombinePostProcess(combineRatio);
  73822. // Set up pipeline
  73823. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73824. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73825. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73826. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73827. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73828. // Finish
  73829. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73830. if (cameras)
  73831. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73832. return _this;
  73833. }
  73834. // Public Methods
  73835. /**
  73836. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73837. */
  73838. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73839. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73840. for (var i = 0; i < this._scene.cameras.length; i++) {
  73841. var camera = this._scene.cameras[i];
  73842. this._originalColorPostProcess.dispose(camera);
  73843. this._ssaoPostProcess.dispose(camera);
  73844. this._blurHPostProcess.dispose(camera);
  73845. this._blurVPostProcess.dispose(camera);
  73846. this._ssaoCombinePostProcess.dispose(camera);
  73847. }
  73848. this._randomTexture.dispose();
  73849. if (disableDepthRender)
  73850. this._scene.disableDepthRenderer();
  73851. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73852. _super.prototype.dispose.call(this);
  73853. };
  73854. // Private Methods
  73855. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73856. var _this = this;
  73857. var size = 16;
  73858. 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);
  73859. 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);
  73860. this._blurHPostProcess.onActivateObservable.add(function () {
  73861. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73862. _this._blurHPostProcess.kernel = size * dw;
  73863. });
  73864. this._blurVPostProcess.onActivateObservable.add(function () {
  73865. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73866. _this._blurVPostProcess.kernel = size * dw;
  73867. });
  73868. };
  73869. SSAORenderingPipeline.prototype._rebuild = function () {
  73870. this._firstUpdate = true;
  73871. _super.prototype._rebuild.call(this);
  73872. };
  73873. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73874. var _this = this;
  73875. var numSamples = 16;
  73876. var sampleSphere = [
  73877. 0.5381, 0.1856, -0.4319,
  73878. 0.1379, 0.2486, 0.4430,
  73879. 0.3371, 0.5679, -0.0057,
  73880. -0.6999, -0.0451, -0.0019,
  73881. 0.0689, -0.1598, -0.8547,
  73882. 0.0560, 0.0069, -0.1843,
  73883. -0.0146, 0.1402, 0.0762,
  73884. 0.0100, -0.1924, -0.0344,
  73885. -0.3577, -0.5301, -0.4358,
  73886. -0.3169, 0.1063, 0.0158,
  73887. 0.0103, -0.5869, 0.0046,
  73888. -0.0897, -0.4940, 0.3287,
  73889. 0.7119, -0.0154, -0.0918,
  73890. -0.0533, 0.0596, -0.5411,
  73891. 0.0352, -0.0631, 0.5460,
  73892. -0.4776, 0.2847, -0.0271
  73893. ];
  73894. var samplesFactor = 1.0 / numSamples;
  73895. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73896. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73897. "area", "fallOff", "base", "range", "viewport"
  73898. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73899. this._ssaoPostProcess.onApply = function (effect) {
  73900. if (_this._firstUpdate) {
  73901. effect.setArray3("sampleSphere", sampleSphere);
  73902. effect.setFloat("samplesFactor", samplesFactor);
  73903. effect.setFloat("randTextureTiles", 4.0);
  73904. }
  73905. effect.setFloat("totalStrength", _this.totalStrength);
  73906. effect.setFloat("radius", _this.radius);
  73907. effect.setFloat("area", _this.area);
  73908. effect.setFloat("fallOff", _this.fallOff);
  73909. effect.setFloat("base", _this.base);
  73910. effect.setTexture("textureSampler", _this._depthTexture);
  73911. effect.setTexture("randomSampler", _this._randomTexture);
  73912. };
  73913. };
  73914. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73915. var _this = this;
  73916. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73917. this._ssaoCombinePostProcess.onApply = function (effect) {
  73918. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73919. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73920. };
  73921. };
  73922. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73923. var size = 512;
  73924. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73925. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73926. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73927. var context = this._randomTexture.getContext();
  73928. var rand = function (min, max) {
  73929. return Math.random() * (max - min) + min;
  73930. };
  73931. var randVector = BABYLON.Vector3.Zero();
  73932. for (var x = 0; x < size; x++) {
  73933. for (var y = 0; y < size; y++) {
  73934. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73935. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73936. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73937. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73938. context.fillRect(x, y, 1, 1);
  73939. }
  73940. }
  73941. this._randomTexture.update(false);
  73942. };
  73943. __decorate([
  73944. BABYLON.serialize()
  73945. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73946. __decorate([
  73947. BABYLON.serialize()
  73948. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73949. __decorate([
  73950. BABYLON.serialize()
  73951. ], SSAORenderingPipeline.prototype, "area", void 0);
  73952. __decorate([
  73953. BABYLON.serialize()
  73954. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73955. __decorate([
  73956. BABYLON.serialize()
  73957. ], SSAORenderingPipeline.prototype, "base", void 0);
  73958. return SSAORenderingPipeline;
  73959. }(BABYLON.PostProcessRenderPipeline));
  73960. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73961. })(BABYLON || (BABYLON = {}));
  73962. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73963. var BABYLON;
  73964. (function (BABYLON) {
  73965. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73966. __extends(SSAO2RenderingPipeline, _super);
  73967. /**
  73968. * @constructor
  73969. * @param {string} name - The rendering pipeline name
  73970. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73971. * @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 }
  73972. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73973. */
  73974. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73975. var _this = _super.call(this, scene.getEngine(), name) || this;
  73976. // Members
  73977. /**
  73978. * The PassPostProcess id in the pipeline that contains the original scene color
  73979. */
  73980. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73981. /**
  73982. * The SSAO PostProcess id in the pipeline
  73983. */
  73984. _this.SSAORenderEffect = "SSAORenderEffect";
  73985. /**
  73986. * The horizontal blur PostProcess id in the pipeline
  73987. */
  73988. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73989. /**
  73990. * The vertical blur PostProcess id in the pipeline
  73991. */
  73992. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73993. /**
  73994. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73995. */
  73996. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73997. /**
  73998. * The output strength of the SSAO post-process. Default value is 1.0.
  73999. */
  74000. _this.totalStrength = 1.0;
  74001. /**
  74002. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74003. */
  74004. _this.maxZ = 100.0;
  74005. /**
  74006. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74007. */
  74008. _this.minZAspect = 0.2;
  74009. /**
  74010. * Number of samples used for the SSAO calculations. Default value is 8
  74011. */
  74012. _this._samples = 8;
  74013. /**
  74014. * Are we using bilateral blur ?
  74015. */
  74016. _this._expensiveBlur = true;
  74017. /**
  74018. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74019. */
  74020. _this.radius = 2.0;
  74021. /**
  74022. * The base color of the SSAO post-process
  74023. * The final result is "base + ssao" between [0, 1]
  74024. */
  74025. _this.base = 0.1;
  74026. _this._firstUpdate = true;
  74027. _this._scene = scene;
  74028. _this._ratio = ratio;
  74029. if (!_this.isSupported) {
  74030. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74031. return _this;
  74032. }
  74033. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74034. var blurRatio = _this._ratio.blurRatio || ratio;
  74035. // Set up assets
  74036. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74037. _this._createRandomTexture();
  74038. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74039. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74040. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74041. _this._createSSAOPostProcess(1.0);
  74042. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74043. _this._createSSAOCombinePostProcess(blurRatio);
  74044. // Set up pipeline
  74045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74047. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74048. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74049. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74050. // Finish
  74051. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74052. if (cameras)
  74053. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74054. return _this;
  74055. }
  74056. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74057. get: function () {
  74058. return this._samples;
  74059. },
  74060. set: function (n) {
  74061. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74062. this._samples = n;
  74063. this._sampleSphere = this._generateHemisphere();
  74064. this._firstUpdate = true;
  74065. },
  74066. enumerable: true,
  74067. configurable: true
  74068. });
  74069. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74070. get: function () {
  74071. return this._expensiveBlur;
  74072. },
  74073. set: function (b) {
  74074. 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"]);
  74075. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74076. this._expensiveBlur = b;
  74077. this._firstUpdate = true;
  74078. },
  74079. enumerable: true,
  74080. configurable: true
  74081. });
  74082. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74083. /**
  74084. * Support test.
  74085. */
  74086. get: function () {
  74087. var engine = BABYLON.Engine.LastCreatedEngine;
  74088. if (!engine) {
  74089. return false;
  74090. }
  74091. return engine.getCaps().drawBuffersExtension;
  74092. },
  74093. enumerable: true,
  74094. configurable: true
  74095. });
  74096. // Public Methods
  74097. /**
  74098. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74099. */
  74100. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74101. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74102. for (var i = 0; i < this._scene.cameras.length; i++) {
  74103. var camera = this._scene.cameras[i];
  74104. this._originalColorPostProcess.dispose(camera);
  74105. this._ssaoPostProcess.dispose(camera);
  74106. this._blurHPostProcess.dispose(camera);
  74107. this._blurVPostProcess.dispose(camera);
  74108. this._ssaoCombinePostProcess.dispose(camera);
  74109. }
  74110. this._randomTexture.dispose();
  74111. if (disableGeometryBufferRenderer)
  74112. this._scene.disableGeometryBufferRenderer();
  74113. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74114. _super.prototype.dispose.call(this);
  74115. };
  74116. // Private Methods
  74117. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74118. var _this = this;
  74119. this._samplerOffsets = [];
  74120. var expensive = this.expensiveBlur;
  74121. for (var i = -8; i < 8; i++) {
  74122. this._samplerOffsets.push(i * 2 + 0.5);
  74123. }
  74124. 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");
  74125. this._blurHPostProcess.onApply = function (effect) {
  74126. if (!_this._scene.activeCamera) {
  74127. return;
  74128. }
  74129. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74130. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74131. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74132. effect.setFloat("radius", _this.radius);
  74133. effect.setTexture("depthSampler", _this._depthTexture);
  74134. if (_this._firstUpdate) {
  74135. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74136. }
  74137. };
  74138. 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");
  74139. this._blurVPostProcess.onApply = function (effect) {
  74140. if (!_this._scene.activeCamera) {
  74141. return;
  74142. }
  74143. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74144. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74145. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74146. effect.setFloat("radius", _this.radius);
  74147. effect.setTexture("depthSampler", _this._depthTexture);
  74148. if (_this._firstUpdate) {
  74149. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74150. _this._firstUpdate = false;
  74151. }
  74152. };
  74153. };
  74154. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74155. this._firstUpdate = true;
  74156. _super.prototype._rebuild.call(this);
  74157. };
  74158. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74159. var numSamples = this.samples;
  74160. var result = [];
  74161. var vector, scale;
  74162. var rand = function (min, max) {
  74163. return Math.random() * (max - min) + min;
  74164. };
  74165. var i = 0;
  74166. while (i < numSamples) {
  74167. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74168. vector.normalize();
  74169. scale = i / numSamples;
  74170. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74171. vector.scaleInPlace(scale);
  74172. result.push(vector.x, vector.y, vector.z);
  74173. i++;
  74174. }
  74175. return result;
  74176. };
  74177. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74178. var _this = this;
  74179. var numSamples = this.samples;
  74180. this._sampleSphere = this._generateHemisphere();
  74181. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74182. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74183. "base", "range", "projection", "near", "far", "texelSize",
  74184. "xViewport", "yViewport", "maxZ", "minZAspect"
  74185. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74186. this._ssaoPostProcess.onApply = function (effect) {
  74187. if (_this._firstUpdate) {
  74188. effect.setArray3("sampleSphere", _this._sampleSphere);
  74189. effect.setFloat("randTextureTiles", 4.0);
  74190. }
  74191. if (!_this._scene.activeCamera) {
  74192. return;
  74193. }
  74194. effect.setFloat("samplesFactor", 1 / _this.samples);
  74195. effect.setFloat("totalStrength", _this.totalStrength);
  74196. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74197. effect.setFloat("radius", _this.radius);
  74198. effect.setFloat("maxZ", _this.maxZ);
  74199. effect.setFloat("minZAspect", _this.minZAspect);
  74200. effect.setFloat("base", _this.base);
  74201. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74202. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74203. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74204. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74205. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74206. effect.setTexture("textureSampler", _this._depthTexture);
  74207. effect.setTexture("normalSampler", _this._normalTexture);
  74208. effect.setTexture("randomSampler", _this._randomTexture);
  74209. };
  74210. };
  74211. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74212. var _this = this;
  74213. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74214. this._ssaoCombinePostProcess.onApply = function (effect) {
  74215. var viewport = _this._scene.activeCamera.viewport;
  74216. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74217. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74218. };
  74219. };
  74220. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74221. var size = 512;
  74222. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74223. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74224. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74225. var context = this._randomTexture.getContext();
  74226. var rand = function (min, max) {
  74227. return Math.random() * (max - min) + min;
  74228. };
  74229. var randVector = BABYLON.Vector3.Zero();
  74230. for (var x = 0; x < size; x++) {
  74231. for (var y = 0; y < size; y++) {
  74232. randVector.x = rand(0.0, 1.0);
  74233. randVector.y = rand(0.0, 1.0);
  74234. randVector.z = 0.0;
  74235. randVector.normalize();
  74236. randVector.scaleInPlace(255);
  74237. randVector.x = Math.floor(randVector.x);
  74238. randVector.y = Math.floor(randVector.y);
  74239. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74240. context.fillRect(x, y, 1, 1);
  74241. }
  74242. }
  74243. this._randomTexture.update(false);
  74244. };
  74245. /**
  74246. * Serialize the rendering pipeline (Used when exporting)
  74247. * @returns the serialized object
  74248. */
  74249. SSAO2RenderingPipeline.prototype.serialize = function () {
  74250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74251. serializationObject.customType = "SSAO2RenderingPipeline";
  74252. return serializationObject;
  74253. };
  74254. /**
  74255. * Parse the serialized pipeline
  74256. * @param source Source pipeline.
  74257. * @param scene The scene to load the pipeline to.
  74258. * @param rootUrl The URL of the serialized pipeline.
  74259. * @returns An instantiated pipeline from the serialized object.
  74260. */
  74261. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74262. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74263. };
  74264. __decorate([
  74265. BABYLON.serialize()
  74266. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74267. __decorate([
  74268. BABYLON.serialize()
  74269. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74270. __decorate([
  74271. BABYLON.serialize()
  74272. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74273. __decorate([
  74274. BABYLON.serialize("samples")
  74275. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74276. __decorate([
  74277. BABYLON.serialize()
  74278. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74279. __decorate([
  74280. BABYLON.serialize("expensiveBlur")
  74281. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74282. __decorate([
  74283. BABYLON.serialize()
  74284. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74285. __decorate([
  74286. BABYLON.serialize()
  74287. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74288. return SSAO2RenderingPipeline;
  74289. }(BABYLON.PostProcessRenderPipeline));
  74290. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74291. })(BABYLON || (BABYLON = {}));
  74292. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74293. // BABYLON.JS Chromatic Aberration GLSL Shader
  74294. // Author: Olivier Guyot
  74295. // Separates very slightly R, G and B colors on the edges of the screen
  74296. // Inspired by Francois Tarlier & Martins Upitis
  74297. var BABYLON;
  74298. (function (BABYLON) {
  74299. var LensRenderingPipeline = /** @class */ (function (_super) {
  74300. __extends(LensRenderingPipeline, _super);
  74301. /**
  74302. * @constructor
  74303. *
  74304. * Effect parameters are as follow:
  74305. * {
  74306. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74307. * edge_blur: number; // from 0 to x (1 for realism)
  74308. * distortion: number; // from 0 to x (1 for realism)
  74309. * grain_amount: number; // from 0 to 1
  74310. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74311. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74312. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74313. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74314. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74315. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74316. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74317. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74318. * }
  74319. * Note: if an effect parameter is unset, effect is disabled
  74320. *
  74321. * @param {string} name - The rendering pipeline name
  74322. * @param {object} parameters - An object containing all parameters (see above)
  74323. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74324. * @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)
  74325. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74326. */
  74327. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74328. if (ratio === void 0) { ratio = 1.0; }
  74329. var _this = _super.call(this, scene.getEngine(), name) || this;
  74330. // Lens effects can be of the following:
  74331. // - chromatic aberration (slight shift of RGB colors)
  74332. // - blur on the edge of the lens
  74333. // - lens distortion
  74334. // - depth-of-field blur & highlights enhancing
  74335. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74336. // - grain effect (noise or custom texture)
  74337. // Two additional texture samplers are needed:
  74338. // - depth map (for depth-of-field)
  74339. // - grain texture
  74340. /**
  74341. * The chromatic aberration PostProcess id in the pipeline
  74342. */
  74343. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74344. /**
  74345. * The highlights enhancing PostProcess id in the pipeline
  74346. */
  74347. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74348. /**
  74349. * The depth-of-field PostProcess id in the pipeline
  74350. */
  74351. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74352. _this._scene = scene;
  74353. // Fetch texture samplers
  74354. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74355. if (parameters.grain_texture) {
  74356. _this._grainTexture = parameters.grain_texture;
  74357. }
  74358. else {
  74359. _this._createGrainTexture();
  74360. }
  74361. // save parameters
  74362. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74363. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74364. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74365. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74366. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74367. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74368. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74369. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74370. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74371. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74372. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74373. // Create effects
  74374. _this._createChromaticAberrationPostProcess(ratio);
  74375. _this._createHighlightsPostProcess(ratio);
  74376. _this._createDepthOfFieldPostProcess(ratio / 4);
  74377. // Set up pipeline
  74378. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74379. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74380. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74381. if (_this._highlightsGain === -1) {
  74382. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74383. }
  74384. // Finish
  74385. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74386. if (cameras) {
  74387. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74388. }
  74389. return _this;
  74390. }
  74391. // public methods (self explanatory)
  74392. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74393. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74394. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74395. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74396. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74397. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74398. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74399. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74400. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74401. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74402. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74403. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74404. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74405. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74406. };
  74407. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74408. this._highlightsPostProcess.updateEffect();
  74409. };
  74410. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74411. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74412. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74413. this._highlightsGain = amount;
  74414. };
  74415. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74416. if (this._highlightsGain === -1) {
  74417. this._highlightsGain = 1.0;
  74418. }
  74419. this._highlightsThreshold = amount;
  74420. };
  74421. LensRenderingPipeline.prototype.disableHighlights = function () {
  74422. this._highlightsGain = -1;
  74423. };
  74424. /**
  74425. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74426. */
  74427. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74428. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74429. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74430. this._chromaticAberrationPostProcess = null;
  74431. this._highlightsPostProcess = null;
  74432. this._depthOfFieldPostProcess = null;
  74433. this._grainTexture.dispose();
  74434. if (disableDepthRender)
  74435. this._scene.disableDepthRenderer();
  74436. };
  74437. // colors shifting and distortion
  74438. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74439. var _this = this;
  74440. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74441. [], // samplers
  74442. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74443. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74444. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74445. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74446. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74447. effect.setFloat('radialIntensity', 1);
  74448. effect.setFloat2('direction', 17, 17);
  74449. effect.setFloat2('centerPosition', 0.5, 0.5);
  74450. };
  74451. };
  74452. // highlights enhancing
  74453. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74454. var _this = this;
  74455. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74456. [], // samplers
  74457. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74458. this._highlightsPostProcess.onApply = function (effect) {
  74459. effect.setFloat('gain', _this._highlightsGain);
  74460. effect.setFloat('threshold', _this._highlightsThreshold);
  74461. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74462. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74463. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74464. };
  74465. };
  74466. // colors shifting and distortion
  74467. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74468. var _this = this;
  74469. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74470. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74471. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74472. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74473. this._depthOfFieldPostProcess.onApply = function (effect) {
  74474. effect.setTexture("depthSampler", _this._depthTexture);
  74475. effect.setTexture("grainSampler", _this._grainTexture);
  74476. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74477. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74478. effect.setFloat('grain_amount', _this._grainAmount);
  74479. effect.setBool('blur_noise', _this._blurNoise);
  74480. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74481. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74482. effect.setFloat('distortion', _this._distortion);
  74483. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74484. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74485. effect.setFloat('aperture', _this._dofAperture);
  74486. effect.setFloat('darken', _this._dofDarken);
  74487. effect.setFloat('edge_blur', _this._edgeBlur);
  74488. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74489. if (_this._scene.activeCamera) {
  74490. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74491. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74492. }
  74493. };
  74494. };
  74495. // creates a black and white random noise texture, 512x512
  74496. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74497. var size = 512;
  74498. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74499. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74500. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74501. var context = this._grainTexture.getContext();
  74502. var rand = function (min, max) {
  74503. return Math.random() * (max - min) + min;
  74504. };
  74505. var value;
  74506. for (var x = 0; x < size; x++) {
  74507. for (var y = 0; y < size; y++) {
  74508. value = Math.floor(rand(0.42, 0.58) * 255);
  74509. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74510. context.fillRect(x, y, 1, 1);
  74511. }
  74512. }
  74513. this._grainTexture.update(false);
  74514. };
  74515. return LensRenderingPipeline;
  74516. }(BABYLON.PostProcessRenderPipeline));
  74517. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74518. })(BABYLON || (BABYLON = {}));
  74519. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74520. var BABYLON;
  74521. (function (BABYLON) {
  74522. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74523. __extends(StandardRenderingPipeline, _super);
  74524. /**
  74525. * @constructor
  74526. * @param {string} name - The rendering pipeline name
  74527. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74528. * @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)
  74529. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74530. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74531. */
  74532. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74533. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74534. var _this = _super.call(this, scene.getEngine(), name) || this;
  74535. _this.downSampleX4PostProcess = null;
  74536. _this.brightPassPostProcess = null;
  74537. _this.blurHPostProcesses = [];
  74538. _this.blurVPostProcesses = [];
  74539. _this.textureAdderPostProcess = null;
  74540. _this.volumetricLightPostProcess = null;
  74541. _this.volumetricLightSmoothXPostProcess = null;
  74542. _this.volumetricLightSmoothYPostProcess = null;
  74543. _this.volumetricLightMergePostProces = null;
  74544. _this.volumetricLightFinalPostProcess = null;
  74545. _this.luminancePostProcess = null;
  74546. _this.luminanceDownSamplePostProcesses = [];
  74547. _this.hdrPostProcess = null;
  74548. _this.textureAdderFinalPostProcess = null;
  74549. _this.lensFlareFinalPostProcess = null;
  74550. _this.hdrFinalPostProcess = null;
  74551. _this.lensFlarePostProcess = null;
  74552. _this.lensFlareComposePostProcess = null;
  74553. _this.motionBlurPostProcess = null;
  74554. _this.depthOfFieldPostProcess = null;
  74555. // Values
  74556. _this.brightThreshold = 1.0;
  74557. _this.blurWidth = 512.0;
  74558. _this.horizontalBlur = false;
  74559. _this.exposure = 1.0;
  74560. _this.lensTexture = null;
  74561. _this.volumetricLightCoefficient = 0.2;
  74562. _this.volumetricLightPower = 4.0;
  74563. _this.volumetricLightBlurScale = 64.0;
  74564. _this.sourceLight = null;
  74565. _this.hdrMinimumLuminance = 1.0;
  74566. _this.hdrDecreaseRate = 0.5;
  74567. _this.hdrIncreaseRate = 0.5;
  74568. _this.lensColorTexture = null;
  74569. _this.lensFlareStrength = 20.0;
  74570. _this.lensFlareGhostDispersal = 1.4;
  74571. _this.lensFlareHaloWidth = 0.7;
  74572. _this.lensFlareDistortionStrength = 16.0;
  74573. _this.lensStarTexture = null;
  74574. _this.lensFlareDirtTexture = null;
  74575. _this.depthOfFieldDistance = 10.0;
  74576. _this.depthOfFieldBlurWidth = 64.0;
  74577. _this.motionStrength = 1.0;
  74578. // IAnimatable
  74579. _this.animations = [];
  74580. _this._currentDepthOfFieldSource = null;
  74581. _this._hdrCurrentLuminance = 1.0;
  74582. // Getters and setters
  74583. _this._bloomEnabled = true;
  74584. _this._depthOfFieldEnabled = false;
  74585. _this._vlsEnabled = false;
  74586. _this._lensFlareEnabled = false;
  74587. _this._hdrEnabled = false;
  74588. _this._motionBlurEnabled = false;
  74589. _this._motionBlurSamples = 64.0;
  74590. _this._volumetricLightStepsCount = 50.0;
  74591. _this._cameras = cameras || [];
  74592. // Initialize
  74593. _this._scene = scene;
  74594. _this._basePostProcess = originalPostProcess;
  74595. _this._ratio = ratio;
  74596. // Misc
  74597. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74598. // Finish
  74599. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74600. _this._buildPipeline();
  74601. return _this;
  74602. }
  74603. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74604. get: function () {
  74605. return this._bloomEnabled;
  74606. },
  74607. set: function (enabled) {
  74608. if (this._bloomEnabled === enabled) {
  74609. return;
  74610. }
  74611. this._bloomEnabled = enabled;
  74612. this._buildPipeline();
  74613. },
  74614. enumerable: true,
  74615. configurable: true
  74616. });
  74617. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74618. get: function () {
  74619. return this._depthOfFieldEnabled;
  74620. },
  74621. set: function (enabled) {
  74622. if (this._depthOfFieldEnabled === enabled) {
  74623. return;
  74624. }
  74625. this._depthOfFieldEnabled = enabled;
  74626. this._buildPipeline();
  74627. },
  74628. enumerable: true,
  74629. configurable: true
  74630. });
  74631. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74632. get: function () {
  74633. return this._lensFlareEnabled;
  74634. },
  74635. set: function (enabled) {
  74636. if (this._lensFlareEnabled === enabled) {
  74637. return;
  74638. }
  74639. this._lensFlareEnabled = enabled;
  74640. this._buildPipeline();
  74641. },
  74642. enumerable: true,
  74643. configurable: true
  74644. });
  74645. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74646. get: function () {
  74647. return this._hdrEnabled;
  74648. },
  74649. set: function (enabled) {
  74650. if (this._hdrEnabled === enabled) {
  74651. return;
  74652. }
  74653. this._hdrEnabled = enabled;
  74654. this._buildPipeline();
  74655. },
  74656. enumerable: true,
  74657. configurable: true
  74658. });
  74659. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74660. get: function () {
  74661. return this._vlsEnabled;
  74662. },
  74663. set: function (enabled) {
  74664. if (this._vlsEnabled === enabled) {
  74665. return;
  74666. }
  74667. if (enabled) {
  74668. var geometry = this._scene.enableGeometryBufferRenderer();
  74669. if (!geometry) {
  74670. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74671. return;
  74672. }
  74673. }
  74674. this._vlsEnabled = enabled;
  74675. this._buildPipeline();
  74676. },
  74677. enumerable: true,
  74678. configurable: true
  74679. });
  74680. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74681. get: function () {
  74682. return this._motionBlurEnabled;
  74683. },
  74684. set: function (enabled) {
  74685. if (this._motionBlurEnabled === enabled) {
  74686. return;
  74687. }
  74688. this._motionBlurEnabled = enabled;
  74689. this._buildPipeline();
  74690. },
  74691. enumerable: true,
  74692. configurable: true
  74693. });
  74694. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74695. get: function () {
  74696. return this._volumetricLightStepsCount;
  74697. },
  74698. set: function (count) {
  74699. if (this.volumetricLightPostProcess) {
  74700. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74701. }
  74702. this._volumetricLightStepsCount = count;
  74703. },
  74704. enumerable: true,
  74705. configurable: true
  74706. });
  74707. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74708. get: function () {
  74709. return this._motionBlurSamples;
  74710. },
  74711. set: function (samples) {
  74712. if (this.motionBlurPostProcess) {
  74713. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74714. }
  74715. this._motionBlurSamples = samples;
  74716. },
  74717. enumerable: true,
  74718. configurable: true
  74719. });
  74720. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74721. var _this = this;
  74722. var ratio = this._ratio;
  74723. var scene = this._scene;
  74724. this._disposePostProcesses();
  74725. this._reset();
  74726. // Create pass post-process
  74727. if (!this._basePostProcess) {
  74728. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74729. this.originalPostProcess.onApply = function (effect) {
  74730. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74731. };
  74732. }
  74733. else {
  74734. this.originalPostProcess = this._basePostProcess;
  74735. }
  74736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74737. this._currentDepthOfFieldSource = this.originalPostProcess;
  74738. if (this._bloomEnabled) {
  74739. // Create down sample X4 post-process
  74740. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74741. // Create bright pass post-process
  74742. this._createBrightPassPostProcess(scene, ratio / 2);
  74743. // Create gaussian blur post-processes (down sampling blurs)
  74744. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74745. // Create texture adder post-process
  74746. this._createTextureAdderPostProcess(scene, ratio);
  74747. // Create depth-of-field source post-process
  74748. 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);
  74749. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74750. }
  74751. if (this._vlsEnabled) {
  74752. // Create volumetric light
  74753. this._createVolumetricLightPostProcess(scene, ratio);
  74754. // Create volumetric light final post-process
  74755. 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);
  74756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74757. }
  74758. if (this._lensFlareEnabled) {
  74759. // Create lens flare post-process
  74760. this._createLensFlarePostProcess(scene, ratio);
  74761. // Create depth-of-field source post-process post lens-flare and disable it now
  74762. 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);
  74763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74764. }
  74765. if (this._hdrEnabled) {
  74766. // Create luminance
  74767. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74768. // Create HDR
  74769. this._createHdrPostProcess(scene, ratio);
  74770. // Create depth-of-field source post-process post hdr and disable it now
  74771. 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);
  74772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74773. }
  74774. if (this._depthOfFieldEnabled) {
  74775. // Create gaussian blur used by depth-of-field
  74776. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74777. // Create depth-of-field post-process
  74778. this._createDepthOfFieldPostProcess(scene, ratio);
  74779. }
  74780. if (this._motionBlurEnabled) {
  74781. // Create motion blur post-process
  74782. this._createMotionBlurPostProcess(scene, ratio);
  74783. }
  74784. if (this._cameras !== null) {
  74785. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74786. }
  74787. };
  74788. // Down Sample X4 Post-Processs
  74789. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74790. var _this = this;
  74791. var downSampleX4Offsets = new Array(32);
  74792. 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);
  74793. this.downSampleX4PostProcess.onApply = function (effect) {
  74794. var id = 0;
  74795. var width = _this.downSampleX4PostProcess.width;
  74796. var height = _this.downSampleX4PostProcess.height;
  74797. for (var i = -2; i < 2; i++) {
  74798. for (var j = -2; j < 2; j++) {
  74799. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74800. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74801. id += 2;
  74802. }
  74803. }
  74804. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74805. };
  74806. // Add to pipeline
  74807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74808. };
  74809. // Brightpass Post-Process
  74810. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74811. var _this = this;
  74812. var brightOffsets = new Array(8);
  74813. 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);
  74814. this.brightPassPostProcess.onApply = function (effect) {
  74815. var sU = (1.0 / _this.brightPassPostProcess.width);
  74816. var sV = (1.0 / _this.brightPassPostProcess.height);
  74817. brightOffsets[0] = -0.5 * sU;
  74818. brightOffsets[1] = 0.5 * sV;
  74819. brightOffsets[2] = 0.5 * sU;
  74820. brightOffsets[3] = 0.5 * sV;
  74821. brightOffsets[4] = -0.5 * sU;
  74822. brightOffsets[5] = -0.5 * sV;
  74823. brightOffsets[6] = 0.5 * sU;
  74824. brightOffsets[7] = -0.5 * sV;
  74825. effect.setArray2("dsOffsets", brightOffsets);
  74826. effect.setFloat("brightThreshold", _this.brightThreshold);
  74827. };
  74828. // Add to pipeline
  74829. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74830. };
  74831. // Create blur H&V post-processes
  74832. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74833. var _this = this;
  74834. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74835. var engine = scene.getEngine();
  74836. 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);
  74837. 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);
  74838. blurX.onActivateObservable.add(function () {
  74839. var dw = blurX.width / engine.getRenderWidth();
  74840. blurX.kernel = _this[blurWidthKey] * dw;
  74841. });
  74842. blurY.onActivateObservable.add(function () {
  74843. var dw = blurY.height / engine.getRenderHeight();
  74844. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74845. });
  74846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74848. this.blurHPostProcesses.push(blurX);
  74849. this.blurVPostProcesses.push(blurY);
  74850. };
  74851. // Create texture adder post-process
  74852. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74853. var _this = this;
  74854. 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);
  74855. this.textureAdderPostProcess.onApply = function (effect) {
  74856. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74857. effect.setTexture("lensSampler", _this.lensTexture);
  74858. effect.setFloat("exposure", _this.exposure);
  74859. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74860. };
  74861. // Add to pipeline
  74862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74863. };
  74864. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74865. var _this = this;
  74866. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74867. geometryRenderer.enablePosition = true;
  74868. var geometry = geometryRenderer.getGBuffer();
  74869. // Base post-process
  74870. 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));
  74871. var depthValues = BABYLON.Vector2.Zero();
  74872. this.volumetricLightPostProcess.onApply = function (effect) {
  74873. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74874. var generator = _this.sourceLight.getShadowGenerator();
  74875. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74876. effect.setTexture("positionSampler", geometry.textures[2]);
  74877. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74878. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74879. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74880. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74881. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74882. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74883. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74884. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74885. effect.setVector2("depthValues", depthValues);
  74886. }
  74887. };
  74888. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74889. // Smooth
  74890. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74891. // Merge
  74892. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74893. this.volumetricLightMergePostProces.onApply = function (effect) {
  74894. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74895. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74896. };
  74897. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74898. };
  74899. // Create luminance
  74900. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74901. var _this = this;
  74902. // Create luminance
  74903. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74904. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74905. var offsets = [];
  74906. this.luminancePostProcess.onApply = function (effect) {
  74907. var sU = (1.0 / _this.luminancePostProcess.width);
  74908. var sV = (1.0 / _this.luminancePostProcess.height);
  74909. offsets[0] = -0.5 * sU;
  74910. offsets[1] = 0.5 * sV;
  74911. offsets[2] = 0.5 * sU;
  74912. offsets[3] = 0.5 * sV;
  74913. offsets[4] = -0.5 * sU;
  74914. offsets[5] = -0.5 * sV;
  74915. offsets[6] = 0.5 * sU;
  74916. offsets[7] = -0.5 * sV;
  74917. effect.setArray2("lumOffsets", offsets);
  74918. };
  74919. // Add to pipeline
  74920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74921. // Create down sample luminance
  74922. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74923. var size = Math.pow(3, i);
  74924. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74925. if (i === 0) {
  74926. defines += "#define FINAL_DOWN_SAMPLER";
  74927. }
  74928. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74929. this.luminanceDownSamplePostProcesses.push(postProcess);
  74930. }
  74931. // Create callbacks and add effects
  74932. var lastLuminance = this.luminancePostProcess;
  74933. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74934. var downSampleOffsets = new Array(18);
  74935. pp.onApply = function (effect) {
  74936. if (!lastLuminance) {
  74937. return;
  74938. }
  74939. var id = 0;
  74940. for (var x = -1; x < 2; x++) {
  74941. for (var y = -1; y < 2; y++) {
  74942. downSampleOffsets[id] = x / lastLuminance.width;
  74943. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74944. id += 2;
  74945. }
  74946. }
  74947. effect.setArray2("dsOffsets", downSampleOffsets);
  74948. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74949. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74950. lastLuminance = _this.luminancePostProcess;
  74951. }
  74952. else {
  74953. lastLuminance = pp;
  74954. }
  74955. };
  74956. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74957. pp.onAfterRender = function (effect) {
  74958. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74959. 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);
  74960. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74961. };
  74962. }
  74963. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74964. });
  74965. };
  74966. // Create HDR post-process
  74967. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74968. var _this = this;
  74969. 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);
  74970. var outputLiminance = 1;
  74971. var time = 0;
  74972. var lastTime = 0;
  74973. this.hdrPostProcess.onApply = function (effect) {
  74974. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74975. time += scene.getEngine().getDeltaTime();
  74976. if (outputLiminance < 0) {
  74977. outputLiminance = _this._hdrCurrentLuminance;
  74978. }
  74979. else {
  74980. var dt = (lastTime - time) / 1000.0;
  74981. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74982. outputLiminance += _this.hdrDecreaseRate * dt;
  74983. }
  74984. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74985. outputLiminance -= _this.hdrIncreaseRate * dt;
  74986. }
  74987. else {
  74988. outputLiminance = _this._hdrCurrentLuminance;
  74989. }
  74990. }
  74991. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74992. effect.setFloat("averageLuminance", outputLiminance);
  74993. lastTime = time;
  74994. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74995. };
  74996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74997. };
  74998. // Create lens flare post-process
  74999. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75000. var _this = this;
  75001. 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);
  75002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75003. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75004. 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);
  75005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75006. var resolution = new BABYLON.Vector2(0, 0);
  75007. // Lens flare
  75008. this.lensFlarePostProcess.onApply = function (effect) {
  75009. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75010. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75011. effect.setFloat("strength", _this.lensFlareStrength);
  75012. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75013. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75014. // Shift
  75015. resolution.x = _this.lensFlarePostProcess.width;
  75016. resolution.y = _this.lensFlarePostProcess.height;
  75017. effect.setVector2("resolution", resolution);
  75018. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75019. };
  75020. // Compose
  75021. 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);
  75022. 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);
  75023. this.lensFlareComposePostProcess.onApply = function (effect) {
  75024. if (!_this._scene.activeCamera) {
  75025. return;
  75026. }
  75027. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75028. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75029. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75030. // Lens start rotation matrix
  75031. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75032. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75033. 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));
  75034. camRot *= 4.0;
  75035. 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);
  75036. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75037. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75038. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75039. };
  75040. };
  75041. // Create depth-of-field post-process
  75042. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75043. var _this = this;
  75044. 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);
  75045. this.depthOfFieldPostProcess.onApply = function (effect) {
  75046. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75047. effect.setTexture("depthSampler", _this._getDepthTexture());
  75048. effect.setFloat("distance", _this.depthOfFieldDistance);
  75049. };
  75050. // Add to pipeline
  75051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75052. };
  75053. // Create motion blur post-process
  75054. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75055. var _this = this;
  75056. 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);
  75057. var motionScale = 0;
  75058. var prevViewProjection = BABYLON.Matrix.Identity();
  75059. var invViewProjection = BABYLON.Matrix.Identity();
  75060. var viewProjection = BABYLON.Matrix.Identity();
  75061. var screenSize = BABYLON.Vector2.Zero();
  75062. this.motionBlurPostProcess.onApply = function (effect) {
  75063. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75064. viewProjection.invertToRef(invViewProjection);
  75065. effect.setMatrix("inverseViewProjection", invViewProjection);
  75066. effect.setMatrix("prevViewProjection", prevViewProjection);
  75067. prevViewProjection = viewProjection;
  75068. screenSize.x = _this.motionBlurPostProcess.width;
  75069. screenSize.y = _this.motionBlurPostProcess.height;
  75070. effect.setVector2("screenSize", screenSize);
  75071. motionScale = scene.getEngine().getFps() / 60.0;
  75072. effect.setFloat("motionScale", motionScale);
  75073. effect.setFloat("motionStrength", _this.motionStrength);
  75074. effect.setTexture("depthSampler", _this._getDepthTexture());
  75075. };
  75076. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75077. };
  75078. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75079. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75080. var renderer = this._scene.enableGeometryBufferRenderer();
  75081. return renderer.getGBuffer().textures[0];
  75082. }
  75083. return this._scene.enableDepthRenderer().getDepthMap();
  75084. };
  75085. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75086. for (var i = 0; i < this._cameras.length; i++) {
  75087. var camera = this._cameras[i];
  75088. if (this.originalPostProcess) {
  75089. this.originalPostProcess.dispose(camera);
  75090. }
  75091. if (this.downSampleX4PostProcess) {
  75092. this.downSampleX4PostProcess.dispose(camera);
  75093. }
  75094. if (this.brightPassPostProcess) {
  75095. this.brightPassPostProcess.dispose(camera);
  75096. }
  75097. if (this.textureAdderPostProcess) {
  75098. this.textureAdderPostProcess.dispose(camera);
  75099. }
  75100. if (this.textureAdderFinalPostProcess) {
  75101. this.textureAdderFinalPostProcess.dispose(camera);
  75102. }
  75103. if (this.volumetricLightPostProcess) {
  75104. this.volumetricLightPostProcess.dispose(camera);
  75105. }
  75106. if (this.volumetricLightSmoothXPostProcess) {
  75107. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75108. }
  75109. if (this.volumetricLightSmoothYPostProcess) {
  75110. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75111. }
  75112. if (this.volumetricLightMergePostProces) {
  75113. this.volumetricLightMergePostProces.dispose(camera);
  75114. }
  75115. if (this.volumetricLightFinalPostProcess) {
  75116. this.volumetricLightFinalPostProcess.dispose(camera);
  75117. }
  75118. if (this.lensFlarePostProcess) {
  75119. this.lensFlarePostProcess.dispose(camera);
  75120. }
  75121. if (this.lensFlareComposePostProcess) {
  75122. this.lensFlareComposePostProcess.dispose(camera);
  75123. }
  75124. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75125. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75126. }
  75127. if (this.luminancePostProcess) {
  75128. this.luminancePostProcess.dispose(camera);
  75129. }
  75130. if (this.hdrPostProcess) {
  75131. this.hdrPostProcess.dispose(camera);
  75132. }
  75133. if (this.hdrFinalPostProcess) {
  75134. this.hdrFinalPostProcess.dispose(camera);
  75135. }
  75136. if (this.depthOfFieldPostProcess) {
  75137. this.depthOfFieldPostProcess.dispose(camera);
  75138. }
  75139. if (this.motionBlurPostProcess) {
  75140. this.motionBlurPostProcess.dispose(camera);
  75141. }
  75142. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75143. this.blurHPostProcesses[j].dispose(camera);
  75144. }
  75145. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75146. this.blurVPostProcesses[j].dispose(camera);
  75147. }
  75148. }
  75149. this.originalPostProcess = null;
  75150. this.downSampleX4PostProcess = null;
  75151. this.brightPassPostProcess = null;
  75152. this.textureAdderPostProcess = null;
  75153. this.textureAdderFinalPostProcess = null;
  75154. this.volumetricLightPostProcess = null;
  75155. this.volumetricLightSmoothXPostProcess = null;
  75156. this.volumetricLightSmoothYPostProcess = null;
  75157. this.volumetricLightMergePostProces = null;
  75158. this.volumetricLightFinalPostProcess = null;
  75159. this.lensFlarePostProcess = null;
  75160. this.lensFlareComposePostProcess = null;
  75161. this.luminancePostProcess = null;
  75162. this.hdrPostProcess = null;
  75163. this.hdrFinalPostProcess = null;
  75164. this.depthOfFieldPostProcess = null;
  75165. this.motionBlurPostProcess = null;
  75166. this.luminanceDownSamplePostProcesses = [];
  75167. this.blurHPostProcesses = [];
  75168. this.blurVPostProcesses = [];
  75169. };
  75170. /**
  75171. * Dispose of the pipeline and stop all post processes
  75172. */
  75173. StandardRenderingPipeline.prototype.dispose = function () {
  75174. this._disposePostProcesses();
  75175. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75176. _super.prototype.dispose.call(this);
  75177. };
  75178. /**
  75179. * Serialize the rendering pipeline (Used when exporting)
  75180. * @returns the serialized object
  75181. */
  75182. StandardRenderingPipeline.prototype.serialize = function () {
  75183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75184. if (this.sourceLight) {
  75185. serializationObject.sourceLightId = this.sourceLight.id;
  75186. }
  75187. serializationObject.customType = "StandardRenderingPipeline";
  75188. return serializationObject;
  75189. };
  75190. /**
  75191. * Parse the serialized pipeline
  75192. * @param source Source pipeline.
  75193. * @param scene The scene to load the pipeline to.
  75194. * @param rootUrl The URL of the serialized pipeline.
  75195. * @returns An instantiated pipeline from the serialized object.
  75196. */
  75197. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75198. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75199. if (source.sourceLightId) {
  75200. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75201. }
  75202. return p;
  75203. };
  75204. // Luminance steps
  75205. StandardRenderingPipeline.LuminanceSteps = 6;
  75206. __decorate([
  75207. BABYLON.serialize()
  75208. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75209. __decorate([
  75210. BABYLON.serialize()
  75211. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75212. __decorate([
  75213. BABYLON.serialize()
  75214. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75215. __decorate([
  75216. BABYLON.serialize()
  75217. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75218. __decorate([
  75219. BABYLON.serializeAsTexture("lensTexture")
  75220. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75221. __decorate([
  75222. BABYLON.serialize()
  75223. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75224. __decorate([
  75225. BABYLON.serialize()
  75226. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75227. __decorate([
  75228. BABYLON.serialize()
  75229. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75230. __decorate([
  75231. BABYLON.serialize()
  75232. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75233. __decorate([
  75234. BABYLON.serialize()
  75235. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75236. __decorate([
  75237. BABYLON.serialize()
  75238. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75239. __decorate([
  75240. BABYLON.serializeAsTexture("lensColorTexture")
  75241. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75242. __decorate([
  75243. BABYLON.serialize()
  75244. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75245. __decorate([
  75246. BABYLON.serialize()
  75247. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75248. __decorate([
  75249. BABYLON.serialize()
  75250. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75251. __decorate([
  75252. BABYLON.serialize()
  75253. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75254. __decorate([
  75255. BABYLON.serializeAsTexture("lensStarTexture")
  75256. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75257. __decorate([
  75258. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75259. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75260. __decorate([
  75261. BABYLON.serialize()
  75262. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75263. __decorate([
  75264. BABYLON.serialize()
  75265. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75266. __decorate([
  75267. BABYLON.serialize()
  75268. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75269. __decorate([
  75270. BABYLON.serialize()
  75271. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75272. __decorate([
  75273. BABYLON.serialize()
  75274. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75275. __decorate([
  75276. BABYLON.serialize()
  75277. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75278. __decorate([
  75279. BABYLON.serialize()
  75280. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75281. __decorate([
  75282. BABYLON.serialize()
  75283. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75284. __decorate([
  75285. BABYLON.serialize()
  75286. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75287. __decorate([
  75288. BABYLON.serialize()
  75289. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75290. __decorate([
  75291. BABYLON.serialize()
  75292. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75293. __decorate([
  75294. BABYLON.serialize()
  75295. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75296. return StandardRenderingPipeline;
  75297. }(BABYLON.PostProcessRenderPipeline));
  75298. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75299. })(BABYLON || (BABYLON = {}));
  75300. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75301. var BABYLON;
  75302. (function (BABYLON) {
  75303. var FxaaPostProcess = /** @class */ (function (_super) {
  75304. __extends(FxaaPostProcess, _super);
  75305. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75306. if (camera === void 0) { camera = null; }
  75307. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75308. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75309. var defines = _this._getDefines();
  75310. _this.updateEffect(defines);
  75311. _this.onApplyObservable.add(function (effect) {
  75312. var texelSize = _this.texelSize;
  75313. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75314. });
  75315. return _this;
  75316. }
  75317. FxaaPostProcess.prototype._getDefines = function () {
  75318. var engine = this.getEngine();
  75319. if (!engine) {
  75320. return null;
  75321. }
  75322. var glInfo = engine.getGlInfo();
  75323. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75324. return "#define MALI 1\n";
  75325. }
  75326. return null;
  75327. };
  75328. return FxaaPostProcess;
  75329. }(BABYLON.PostProcess));
  75330. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75331. })(BABYLON || (BABYLON = {}));
  75332. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75333. var BABYLON;
  75334. (function (BABYLON) {
  75335. /**
  75336. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75337. */
  75338. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75339. __extends(ChromaticAberrationPostProcess, _super);
  75340. /**
  75341. * Creates a new instance ChromaticAberrationPostProcess
  75342. * @param name The name of the effect.
  75343. * @param screenWidth The width of the screen to apply the effect on.
  75344. * @param screenHeight The height of the screen to apply the effect on.
  75345. * @param options The required width/height ratio to downsize to before computing the render pass.
  75346. * @param camera The camera to apply the render pass to.
  75347. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75348. * @param engine The engine which the post process will be applied. (default: current engine)
  75349. * @param reusable If the post process can be reused on the same frame. (default: false)
  75350. * @param textureType Type of textures used when performing the post process. (default: 0)
  75351. * @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)
  75352. */
  75353. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75355. if (blockCompilation === void 0) { blockCompilation = false; }
  75356. 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;
  75357. /**
  75358. * The amount of seperation of rgb channels (default: 30)
  75359. */
  75360. _this.aberrationAmount = 30;
  75361. /**
  75362. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75363. */
  75364. _this.radialIntensity = 0;
  75365. /**
  75366. * 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))
  75367. */
  75368. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75369. /**
  75370. * 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))
  75371. */
  75372. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75373. _this.onApplyObservable.add(function (effect) {
  75374. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75375. effect.setFloat('screen_width', screenWidth);
  75376. effect.setFloat('screen_height', screenHeight);
  75377. effect.setFloat('radialIntensity', _this.radialIntensity);
  75378. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75379. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75380. });
  75381. return _this;
  75382. }
  75383. return ChromaticAberrationPostProcess;
  75384. }(BABYLON.PostProcess));
  75385. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75386. })(BABYLON || (BABYLON = {}));
  75387. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75388. var BABYLON;
  75389. (function (BABYLON) {
  75390. /**
  75391. * The GrainPostProcess adds noise to the image at mid luminance levels
  75392. */
  75393. var GrainPostProcess = /** @class */ (function (_super) {
  75394. __extends(GrainPostProcess, _super);
  75395. /**
  75396. * Creates a new instance of @see GrainPostProcess
  75397. * @param name The name of the effect.
  75398. * @param options The required width/height ratio to downsize to before computing the render pass.
  75399. * @param camera The camera to apply the render pass to.
  75400. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75401. * @param engine The engine which the post process will be applied. (default: current engine)
  75402. * @param reusable If the post process can be reused on the same frame. (default: false)
  75403. * @param textureType Type of textures used when performing the post process. (default: 0)
  75404. * @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)
  75405. */
  75406. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75407. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75408. if (blockCompilation === void 0) { blockCompilation = false; }
  75409. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75410. /**
  75411. * The intensity of the grain added (default: 30)
  75412. */
  75413. _this.intensity = 30;
  75414. /**
  75415. * If the grain should be randomized on every frame
  75416. */
  75417. _this.animated = false;
  75418. _this.onApplyObservable.add(function (effect) {
  75419. effect.setFloat('intensity', _this.intensity);
  75420. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75421. });
  75422. return _this;
  75423. }
  75424. return GrainPostProcess;
  75425. }(BABYLON.PostProcess));
  75426. BABYLON.GrainPostProcess = GrainPostProcess;
  75427. })(BABYLON || (BABYLON = {}));
  75428. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75429. var BABYLON;
  75430. (function (BABYLON) {
  75431. /**
  75432. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75433. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75434. */
  75435. var SharpenPostProcess = /** @class */ (function (_super) {
  75436. __extends(SharpenPostProcess, _super);
  75437. /**
  75438. * Creates a new instance ConvolutionPostProcess
  75439. * @param name The name of the effect.
  75440. * @param options The required width/height ratio to downsize to before computing the render pass.
  75441. * @param camera The camera to apply the render pass to.
  75442. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75443. * @param engine The engine which the post process will be applied. (default: current engine)
  75444. * @param reusable If the post process can be reused on the same frame. (default: false)
  75445. * @param textureType Type of textures used when performing the post process. (default: 0)
  75446. * @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)
  75447. */
  75448. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75449. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75450. if (blockCompilation === void 0) { blockCompilation = false; }
  75451. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75452. /**
  75453. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75454. */
  75455. _this.colorAmount = 1.0;
  75456. /**
  75457. * How much sharpness should be applied (default: 0.3)
  75458. */
  75459. _this.edgeAmount = 0.3;
  75460. _this.onApply = function (effect) {
  75461. effect.setFloat2("screenSize", _this.width, _this.height);
  75462. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75463. };
  75464. return _this;
  75465. }
  75466. return SharpenPostProcess;
  75467. }(BABYLON.PostProcess));
  75468. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75469. })(BABYLON || (BABYLON = {}));
  75470. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75471. var BABYLON;
  75472. (function (BABYLON) {
  75473. /**
  75474. * The Blur Post Process which blurs an image based on a kernel and direction.
  75475. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75476. */
  75477. var BlurPostProcess = /** @class */ (function (_super) {
  75478. __extends(BlurPostProcess, _super);
  75479. /**
  75480. * Creates a new instance BlurPostProcess
  75481. * @param name The name of the effect.
  75482. * @param direction The direction in which to blur the image.
  75483. * @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.
  75484. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75485. * @param camera The camera to apply the render pass to.
  75486. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75487. * @param engine The engine which the post process will be applied. (default: current engine)
  75488. * @param reusable If the post process can be reused on the same frame. (default: false)
  75489. * @param textureType Type of textures used when performing the post process. (default: 0)
  75490. * @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)
  75491. */
  75492. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75493. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75495. if (defines === void 0) { defines = ""; }
  75496. if (blockCompilation === void 0) { blockCompilation = false; }
  75497. 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;
  75498. _this.direction = direction;
  75499. _this.blockCompilation = blockCompilation;
  75500. _this._packedFloat = false;
  75501. _this._staticDefines = "";
  75502. _this._staticDefines = defines;
  75503. _this.onApplyObservable.add(function (effect) {
  75504. if (_this._outputTexture) {
  75505. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75506. }
  75507. else {
  75508. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75509. }
  75510. });
  75511. _this.kernel = kernel;
  75512. return _this;
  75513. }
  75514. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75515. /**
  75516. * Gets the length in pixels of the blur sample region
  75517. */
  75518. get: function () {
  75519. return this._idealKernel;
  75520. },
  75521. /**
  75522. * Sets the length in pixels of the blur sample region
  75523. */
  75524. set: function (v) {
  75525. if (this._idealKernel === v) {
  75526. return;
  75527. }
  75528. v = Math.max(v, 1);
  75529. this._idealKernel = v;
  75530. this._kernel = this._nearestBestKernel(v);
  75531. if (!this.blockCompilation) {
  75532. this._updateParameters();
  75533. }
  75534. },
  75535. enumerable: true,
  75536. configurable: true
  75537. });
  75538. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75539. /**
  75540. * Gets wether or not the blur is unpacking/repacking floats
  75541. */
  75542. get: function () {
  75543. return this._packedFloat;
  75544. },
  75545. /**
  75546. * Sets wether or not the blur needs to unpack/repack floats
  75547. */
  75548. set: function (v) {
  75549. if (this._packedFloat === v) {
  75550. return;
  75551. }
  75552. this._packedFloat = v;
  75553. if (!this.blockCompilation) {
  75554. this._updateParameters();
  75555. }
  75556. },
  75557. enumerable: true,
  75558. configurable: true
  75559. });
  75560. /**
  75561. * Updates the effect with the current post process compile time values and recompiles the shader.
  75562. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75563. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75564. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75565. * @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
  75566. * @param onCompiled Called when the shader has been compiled.
  75567. * @param onError Called if there is an error when compiling a shader.
  75568. */
  75569. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75570. if (defines === void 0) { defines = null; }
  75571. if (uniforms === void 0) { uniforms = null; }
  75572. if (samplers === void 0) { samplers = null; }
  75573. this._updateParameters(onCompiled, onError);
  75574. };
  75575. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75576. // Generate sampling offsets and weights
  75577. var N = this._kernel;
  75578. var centerIndex = (N - 1) / 2;
  75579. // Generate Gaussian sampling weights over kernel
  75580. var offsets = [];
  75581. var weights = [];
  75582. var totalWeight = 0;
  75583. for (var i = 0; i < N; i++) {
  75584. var u = i / (N - 1);
  75585. var w = this._gaussianWeight(u * 2.0 - 1);
  75586. offsets[i] = (i - centerIndex);
  75587. weights[i] = w;
  75588. totalWeight += w;
  75589. }
  75590. // Normalize weights
  75591. for (var i = 0; i < weights.length; i++) {
  75592. weights[i] /= totalWeight;
  75593. }
  75594. // Optimize: combine samples to take advantage of hardware linear sampling
  75595. // Walk from left to center, combining pairs (symmetrically)
  75596. var linearSamplingWeights = [];
  75597. var linearSamplingOffsets = [];
  75598. var linearSamplingMap = [];
  75599. for (var i = 0; i <= centerIndex; i += 2) {
  75600. var j = Math.min(i + 1, Math.floor(centerIndex));
  75601. var singleCenterSample = i === j;
  75602. if (singleCenterSample) {
  75603. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75604. }
  75605. else {
  75606. var sharedCell = j === centerIndex;
  75607. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75608. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75609. if (offsetLinear === 0) {
  75610. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75611. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75612. }
  75613. else {
  75614. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75615. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75616. }
  75617. }
  75618. }
  75619. for (var i = 0; i < linearSamplingMap.length; i++) {
  75620. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75621. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75622. }
  75623. // Replace with optimized
  75624. offsets = linearSamplingOffsets;
  75625. weights = linearSamplingWeights;
  75626. // Generate shaders
  75627. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75628. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75629. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75630. var defines = "";
  75631. defines += this._staticDefines;
  75632. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75633. if (this._staticDefines.indexOf("DOF") != -1) {
  75634. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75635. varyingCount--;
  75636. }
  75637. for (var i = 0; i < varyingCount; i++) {
  75638. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75639. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75640. }
  75641. var depCount = 0;
  75642. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75643. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75644. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75645. depCount++;
  75646. }
  75647. if (this.packedFloat) {
  75648. defines += "#define PACKEDFLOAT 1";
  75649. }
  75650. this.blockCompilation = false;
  75651. _super.prototype.updateEffect.call(this, defines, null, null, {
  75652. varyingCount: varyingCount,
  75653. depCount: depCount
  75654. }, onCompiled, onError);
  75655. };
  75656. /**
  75657. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75658. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75659. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75660. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75661. * The gaps between physical kernels are compensated for in the weighting of the samples
  75662. * @param idealKernel Ideal blur kernel.
  75663. * @return Nearest best kernel.
  75664. */
  75665. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75666. var v = Math.round(idealKernel);
  75667. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75668. var k = _a[_i];
  75669. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75670. return Math.max(k, 3);
  75671. }
  75672. }
  75673. return Math.max(v, 3);
  75674. };
  75675. /**
  75676. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75677. * @param x The point on the Gaussian distribution to sample.
  75678. * @return the value of the Gaussian function at x.
  75679. */
  75680. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75681. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75682. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75683. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75684. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75685. // truncated at around 1.3% of peak strength.
  75686. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75687. var sigma = (1 / 3);
  75688. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75689. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75690. var weight = (1.0 / denominator) * Math.exp(exponent);
  75691. return weight;
  75692. };
  75693. /**
  75694. * Generates a string that can be used as a floating point number in GLSL.
  75695. * @param x Value to print.
  75696. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75697. * @return GLSL float string.
  75698. */
  75699. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75700. if (decimalFigures === void 0) { decimalFigures = 8; }
  75701. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75702. };
  75703. return BlurPostProcess;
  75704. }(BABYLON.PostProcess));
  75705. BABYLON.BlurPostProcess = BlurPostProcess;
  75706. })(BABYLON || (BABYLON = {}));
  75707. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75708. var BABYLON;
  75709. (function (BABYLON) {
  75710. /**
  75711. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75712. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75713. * based on samples that have a large difference in distance than the center pixel.
  75714. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75715. */
  75716. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75717. __extends(DepthOfFieldBlurPostProcess, _super);
  75718. /**
  75719. * Creates a new instance CircleOfConfusionPostProcess
  75720. * @param name The name of the effect.
  75721. * @param scene The scene the effect belongs to.
  75722. * @param direction The direction the blur should be applied.
  75723. * @param kernel The size of the kernel used to blur.
  75724. * @param options The required width/height ratio to downsize to before computing the render pass.
  75725. * @param camera The camera to apply the render pass to.
  75726. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75727. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75728. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75729. * @param engine The engine which the post process will be applied. (default: current engine)
  75730. * @param reusable If the post process can be reused on the same frame. (default: false)
  75731. * @param textureType Type of textures used when performing the post process. (default: 0)
  75732. * @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)
  75733. */
  75734. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75735. if (imageToBlur === void 0) { imageToBlur = null; }
  75736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75738. if (blockCompilation === void 0) { blockCompilation = false; }
  75739. 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;
  75740. _this.direction = direction;
  75741. _this.onApplyObservable.add(function (effect) {
  75742. if (imageToBlur != null) {
  75743. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75744. }
  75745. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75746. if (scene.activeCamera) {
  75747. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75748. }
  75749. });
  75750. return _this;
  75751. }
  75752. return DepthOfFieldBlurPostProcess;
  75753. }(BABYLON.BlurPostProcess));
  75754. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75755. })(BABYLON || (BABYLON = {}));
  75756. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75757. var BABYLON;
  75758. (function (BABYLON) {
  75759. /**
  75760. * Options to be set when merging outputs from the default pipeline.
  75761. */
  75762. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75763. function DepthOfFieldMergePostProcessOptions() {
  75764. }
  75765. return DepthOfFieldMergePostProcessOptions;
  75766. }());
  75767. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75768. /**
  75769. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75770. */
  75771. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75772. __extends(DepthOfFieldMergePostProcess, _super);
  75773. /**
  75774. * Creates a new instance of DepthOfFieldMergePostProcess
  75775. * @param name The name of the effect.
  75776. * @param originalFromInput Post process which's input will be used for the merge.
  75777. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75778. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75779. * @param options The required width/height ratio to downsize to before computing the render pass.
  75780. * @param camera The camera to apply the render pass to.
  75781. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75782. * @param engine The engine which the post process will be applied. (default: current engine)
  75783. * @param reusable If the post process can be reused on the same frame. (default: false)
  75784. * @param textureType Type of textures used when performing the post process. (default: 0)
  75785. * @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)
  75786. */
  75787. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75788. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75789. if (blockCompilation === void 0) { blockCompilation = false; }
  75790. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75791. _this.blurSteps = blurSteps;
  75792. _this.onApplyObservable.add(function (effect) {
  75793. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75794. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75795. blurSteps.forEach(function (step, index) {
  75796. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75797. });
  75798. });
  75799. if (!blockCompilation) {
  75800. _this.updateEffect();
  75801. }
  75802. return _this;
  75803. }
  75804. /**
  75805. * Updates the effect with the current post process compile time values and recompiles the shader.
  75806. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75807. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75808. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75809. * @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
  75810. * @param onCompiled Called when the shader has been compiled.
  75811. * @param onError Called if there is an error when compiling a shader.
  75812. */
  75813. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75814. if (defines === void 0) { defines = null; }
  75815. if (uniforms === void 0) { uniforms = null; }
  75816. if (samplers === void 0) { samplers = null; }
  75817. if (!defines) {
  75818. defines = "";
  75819. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75820. }
  75821. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75822. };
  75823. return DepthOfFieldMergePostProcess;
  75824. }(BABYLON.PostProcess));
  75825. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75826. })(BABYLON || (BABYLON = {}));
  75827. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75828. var BABYLON;
  75829. (function (BABYLON) {
  75830. /**
  75831. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75832. */
  75833. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75834. __extends(CircleOfConfusionPostProcess, _super);
  75835. /**
  75836. * Creates a new instance CircleOfConfusionPostProcess
  75837. * @param name The name of the effect.
  75838. * @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.
  75839. * @param options The required width/height ratio to downsize to before computing the render pass.
  75840. * @param camera The camera to apply the render pass to.
  75841. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75842. * @param engine The engine which the post process will be applied. (default: current engine)
  75843. * @param reusable If the post process can be reused on the same frame. (default: false)
  75844. * @param textureType Type of textures used when performing the post process. (default: 0)
  75845. * @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)
  75846. */
  75847. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75848. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75849. if (blockCompilation === void 0) { blockCompilation = false; }
  75850. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75851. /**
  75852. * 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.
  75853. */
  75854. _this.lensSize = 50;
  75855. /**
  75856. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75857. */
  75858. _this.fStop = 1.4;
  75859. /**
  75860. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75861. */
  75862. _this.focusDistance = 2000;
  75863. /**
  75864. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75865. */
  75866. _this.focalLength = 50;
  75867. _this._depthTexture = null;
  75868. _this._depthTexture = depthTexture;
  75869. _this.onApplyObservable.add(function (effect) {
  75870. if (!_this._depthTexture) {
  75871. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75872. return;
  75873. }
  75874. effect.setTexture("depthSampler", _this._depthTexture);
  75875. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75876. var aperture = _this.lensSize / _this.fStop;
  75877. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75878. effect.setFloat('focusDistance', _this.focusDistance);
  75879. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75880. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75881. });
  75882. return _this;
  75883. }
  75884. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75885. /**
  75886. * 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.
  75887. */
  75888. set: function (value) {
  75889. this._depthTexture = value;
  75890. },
  75891. enumerable: true,
  75892. configurable: true
  75893. });
  75894. return CircleOfConfusionPostProcess;
  75895. }(BABYLON.PostProcess));
  75896. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75897. })(BABYLON || (BABYLON = {}));
  75898. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75899. var BABYLON;
  75900. (function (BABYLON) {
  75901. /**
  75902. * Specifies the level of max blur that should be applied when using the depth of field effect
  75903. */
  75904. var DepthOfFieldEffectBlurLevel;
  75905. (function (DepthOfFieldEffectBlurLevel) {
  75906. /**
  75907. * Subtle blur
  75908. */
  75909. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75910. /**
  75911. * Medium blur
  75912. */
  75913. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75914. /**
  75915. * Large blur
  75916. */
  75917. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75918. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75919. ;
  75920. /**
  75921. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75922. */
  75923. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75924. __extends(DepthOfFieldEffect, _super);
  75925. /**
  75926. * Creates a new instance DepthOfFieldEffect
  75927. * @param scene The scene the effect belongs to.
  75928. * @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.
  75929. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75930. * @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)
  75931. */
  75932. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75933. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75934. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75935. if (blockCompilation === void 0) { blockCompilation = false; }
  75936. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75937. return _this._effects;
  75938. }, true) || this;
  75939. /**
  75940. * Internal post processes in depth of field effect
  75941. */
  75942. _this._effects = [];
  75943. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75944. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75945. // 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)
  75946. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75947. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75948. _this._depthOfFieldBlurY = [];
  75949. _this._depthOfFieldBlurX = [];
  75950. var blurCount = 1;
  75951. var kernelSize = 15;
  75952. switch (blurLevel) {
  75953. case DepthOfFieldEffectBlurLevel.High: {
  75954. blurCount = 3;
  75955. kernelSize = 51;
  75956. break;
  75957. }
  75958. case DepthOfFieldEffectBlurLevel.Medium: {
  75959. blurCount = 2;
  75960. kernelSize = 31;
  75961. break;
  75962. }
  75963. default: {
  75964. kernelSize = 15;
  75965. blurCount = 1;
  75966. break;
  75967. }
  75968. }
  75969. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75970. var ratio = 1.0;
  75971. for (var i = 0; i < blurCount; i++) {
  75972. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75973. blurY.autoClear = false;
  75974. ratio = 0.75 / Math.pow(2, i);
  75975. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75976. blurX.autoClear = false;
  75977. _this._depthOfFieldBlurY.push(blurY);
  75978. _this._depthOfFieldBlurX.push(blurX);
  75979. }
  75980. // Set all post processes on the effect.
  75981. _this._effects = [_this._circleOfConfusion];
  75982. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75983. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75984. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75985. }
  75986. // Merge blurred images with original image based on circleOfConfusion
  75987. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75988. _this._dofMerge.autoClear = false;
  75989. _this._effects.push(_this._dofMerge);
  75990. return _this;
  75991. }
  75992. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75993. get: function () {
  75994. return this._circleOfConfusion.focalLength;
  75995. },
  75996. /**
  75997. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75998. */
  75999. set: function (value) {
  76000. this._circleOfConfusion.focalLength = value;
  76001. },
  76002. enumerable: true,
  76003. configurable: true
  76004. });
  76005. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76006. get: function () {
  76007. return this._circleOfConfusion.fStop;
  76008. },
  76009. /**
  76010. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76011. */
  76012. set: function (value) {
  76013. this._circleOfConfusion.fStop = value;
  76014. },
  76015. enumerable: true,
  76016. configurable: true
  76017. });
  76018. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76019. get: function () {
  76020. return this._circleOfConfusion.focusDistance;
  76021. },
  76022. /**
  76023. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76024. */
  76025. set: function (value) {
  76026. this._circleOfConfusion.focusDistance = value;
  76027. },
  76028. enumerable: true,
  76029. configurable: true
  76030. });
  76031. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76032. get: function () {
  76033. return this._circleOfConfusion.lensSize;
  76034. },
  76035. /**
  76036. * 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.
  76037. */
  76038. set: function (value) {
  76039. this._circleOfConfusion.lensSize = value;
  76040. },
  76041. enumerable: true,
  76042. configurable: true
  76043. });
  76044. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76045. /**
  76046. * 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.
  76047. */
  76048. set: function (value) {
  76049. this._circleOfConfusion.depthTexture = value;
  76050. },
  76051. enumerable: true,
  76052. configurable: true
  76053. });
  76054. /**
  76055. * Disposes each of the internal effects for a given camera.
  76056. * @param camera The camera to dispose the effect on.
  76057. */
  76058. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76059. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76060. this._effects[effectIndex].dispose(camera);
  76061. }
  76062. };
  76063. /**
  76064. * Internal
  76065. */
  76066. DepthOfFieldEffect.prototype._updateEffects = function () {
  76067. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76068. this._effects[effectIndex].updateEffect();
  76069. }
  76070. };
  76071. /**
  76072. * Internal
  76073. * @returns if all the contained post processes are ready.
  76074. */
  76075. DepthOfFieldEffect.prototype._isReady = function () {
  76076. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76077. if (!this._effects[effectIndex].isReady()) {
  76078. return false;
  76079. }
  76080. }
  76081. return true;
  76082. };
  76083. return DepthOfFieldEffect;
  76084. }(BABYLON.PostProcessRenderEffect));
  76085. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76086. })(BABYLON || (BABYLON = {}));
  76087. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76088. var BABYLON;
  76089. (function (BABYLON) {
  76090. /**
  76091. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76092. */
  76093. var BloomMergePostProcess = /** @class */ (function (_super) {
  76094. __extends(BloomMergePostProcess, _super);
  76095. /**
  76096. * Creates a new instance of @see BloomMergePostProcess
  76097. * @param name The name of the effect.
  76098. * @param originalFromInput Post process which's input will be used for the merge.
  76099. * @param blurred Blurred highlights post process which's output will be used.
  76100. * @param weight Weight of the bloom to be added to the original input.
  76101. * @param options The required width/height ratio to downsize to before computing the render pass.
  76102. * @param camera The camera to apply the render pass to.
  76103. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76104. * @param engine The engine which the post process will be applied. (default: current engine)
  76105. * @param reusable If the post process can be reused on the same frame. (default: false)
  76106. * @param textureType Type of textures used when performing the post process. (default: 0)
  76107. * @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)
  76108. */
  76109. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76110. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76111. if (blockCompilation === void 0) { blockCompilation = false; }
  76112. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76113. _this.weight = weight;
  76114. _this.onApplyObservable.add(function (effect) {
  76115. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76116. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76117. effect.setFloat("bloomWeight", _this.weight);
  76118. });
  76119. if (!blockCompilation) {
  76120. _this.updateEffect();
  76121. }
  76122. return _this;
  76123. }
  76124. return BloomMergePostProcess;
  76125. }(BABYLON.PostProcess));
  76126. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76127. })(BABYLON || (BABYLON = {}));
  76128. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76129. var BABYLON;
  76130. (function (BABYLON) {
  76131. /**
  76132. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  76133. */
  76134. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76135. __extends(ExtractHighlightsPostProcess, _super);
  76136. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76137. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76138. if (blockCompilation === void 0) { blockCompilation = false; }
  76139. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76140. /**
  76141. * The luminance threshold, pixels below this value will be set to black.
  76142. */
  76143. _this.threshold = 0.9;
  76144. /**
  76145. * Internal
  76146. */
  76147. _this._exposure = 1;
  76148. /**
  76149. * Post process which has the input texture to be used when performing highlight extraction
  76150. */
  76151. _this._inputPostProcess = null;
  76152. _this.onApplyObservable.add(function (effect) {
  76153. if (_this._inputPostProcess) {
  76154. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76155. }
  76156. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76157. effect.setFloat('exposure', _this._exposure);
  76158. });
  76159. return _this;
  76160. }
  76161. return ExtractHighlightsPostProcess;
  76162. }(BABYLON.PostProcess));
  76163. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76164. })(BABYLON || (BABYLON = {}));
  76165. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76166. var BABYLON;
  76167. (function (BABYLON) {
  76168. /**
  76169. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76170. */
  76171. var BloomEffect = /** @class */ (function (_super) {
  76172. __extends(BloomEffect, _super);
  76173. /**
  76174. * Creates a new instance of @see BloomEffect
  76175. * @param scene The scene the effect belongs to.
  76176. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76177. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76178. * @param bloomWeight The the strength of bloom.
  76179. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76180. * @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)
  76181. */
  76182. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76183. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76184. if (blockCompilation === void 0) { blockCompilation = false; }
  76185. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76186. return _this._effects;
  76187. }, true) || this;
  76188. _this.bloomScale = bloomScale;
  76189. /**
  76190. * Internal
  76191. */
  76192. _this._effects = [];
  76193. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76194. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  76195. _this._blurX.alwaysForcePOT = true;
  76196. _this._blurX.autoClear = false;
  76197. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  76198. _this._blurY.alwaysForcePOT = true;
  76199. _this._blurY.autoClear = false;
  76200. _this.kernel = bloomKernel;
  76201. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76202. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76203. _this._merge.autoClear = false;
  76204. _this._effects.push(_this._merge);
  76205. return _this;
  76206. }
  76207. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76208. /**
  76209. * The luminance threshold to find bright areas of the image to bloom.
  76210. */
  76211. get: function () {
  76212. return this._downscale.threshold;
  76213. },
  76214. set: function (value) {
  76215. this._downscale.threshold = value;
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(BloomEffect.prototype, "weight", {
  76221. /**
  76222. * The strength of the bloom.
  76223. */
  76224. get: function () {
  76225. return this._merge.weight;
  76226. },
  76227. set: function (value) {
  76228. this._merge.weight = value;
  76229. },
  76230. enumerable: true,
  76231. configurable: true
  76232. });
  76233. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76234. /**
  76235. * Specifies the size of the bloom blur kernel, relative to the final output size
  76236. */
  76237. get: function () {
  76238. return this._blurX.kernel / this.bloomScale;
  76239. },
  76240. set: function (value) {
  76241. this._blurX.kernel = value * this.bloomScale;
  76242. this._blurY.kernel = value * this.bloomScale;
  76243. },
  76244. enumerable: true,
  76245. configurable: true
  76246. });
  76247. /**
  76248. * Disposes each of the internal effects for a given camera.
  76249. * @param camera The camera to dispose the effect on.
  76250. */
  76251. BloomEffect.prototype.disposeEffects = function (camera) {
  76252. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76253. this._effects[effectIndex].dispose(camera);
  76254. }
  76255. };
  76256. /**
  76257. * Internal
  76258. */
  76259. BloomEffect.prototype._updateEffects = function () {
  76260. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76261. this._effects[effectIndex].updateEffect();
  76262. }
  76263. };
  76264. /**
  76265. * Internal
  76266. * @returns if all the contained post processes are ready.
  76267. */
  76268. BloomEffect.prototype._isReady = function () {
  76269. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76270. if (!this._effects[effectIndex].isReady()) {
  76271. return false;
  76272. }
  76273. }
  76274. return true;
  76275. };
  76276. return BloomEffect;
  76277. }(BABYLON.PostProcessRenderEffect));
  76278. BABYLON.BloomEffect = BloomEffect;
  76279. })(BABYLON || (BABYLON = {}));
  76280. //# sourceMappingURL=babylon.bloomEffect.js.map
  76281. var BABYLON;
  76282. (function (BABYLON) {
  76283. /**
  76284. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76285. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76286. */
  76287. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76288. __extends(DefaultRenderingPipeline, _super);
  76289. /**
  76290. * @constructor
  76291. * @param {string} name - The rendering pipeline name (default: "")
  76292. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76293. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76294. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76295. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76296. */
  76297. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76298. if (name === void 0) { name = ""; }
  76299. if (hdr === void 0) { hdr = true; }
  76300. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76301. if (automaticBuild === void 0) { automaticBuild = true; }
  76302. var _this = _super.call(this, scene.getEngine(), name) || this;
  76303. _this._originalCameras = [];
  76304. /**
  76305. * ID of the sharpen post process,
  76306. */
  76307. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76308. /**
  76309. * ID of the image processing post process;
  76310. */
  76311. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76312. /**
  76313. * ID of the Fast Approximate Anti-Aliasing post process;
  76314. */
  76315. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76316. /**
  76317. * ID of the chromatic aberration post process,
  76318. */
  76319. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76320. /**
  76321. * ID of the grain post process
  76322. */
  76323. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76324. /**
  76325. * Glow post process which adds a glow to emmisive areas of the image
  76326. */
  76327. _this._glowLayer = null;
  76328. /**
  76329. * Animations which can be used to tweak settings over a period of time
  76330. */
  76331. _this.animations = [];
  76332. _this._imageProcessingConfigurationObserver = null;
  76333. // Values
  76334. _this._sharpenEnabled = false;
  76335. _this._bloomEnabled = false;
  76336. _this._depthOfFieldEnabled = false;
  76337. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76338. _this._fxaaEnabled = false;
  76339. _this._imageProcessingEnabled = true;
  76340. _this._bloomScale = 0.5;
  76341. _this._chromaticAberrationEnabled = false;
  76342. _this._grainEnabled = false;
  76343. _this._buildAllowed = true;
  76344. _this._resizeObserver = null;
  76345. _this._hardwareScaleLevel = 1.0;
  76346. _this._bloomKernel = 64;
  76347. /**
  76348. * Specifies the weight of the bloom in the final rendering
  76349. */
  76350. _this._bloomWeight = 0.15;
  76351. /**
  76352. * Specifies the luma threshold for the area that will be blurred by the bloom
  76353. */
  76354. _this._bloomThreshold = 0.9;
  76355. _this._samples = 1;
  76356. _this._hasCleared = false;
  76357. _this._prevPostProcess = null;
  76358. _this._prevPrevPostProcess = null;
  76359. _this._cameras = cameras || scene.cameras;
  76360. _this._originalCameras = _this._cameras.slice();
  76361. _this._buildAllowed = automaticBuild;
  76362. // Initialize
  76363. _this._scene = scene;
  76364. var caps = _this._scene.getEngine().getCaps();
  76365. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76366. // Misc
  76367. if (_this._hdr) {
  76368. if (caps.textureHalfFloatRender) {
  76369. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76370. }
  76371. else if (caps.textureFloatRender) {
  76372. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76373. }
  76374. }
  76375. else {
  76376. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76377. }
  76378. // Attach
  76379. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76380. var engine = _this._scene.getEngine();
  76381. // Create post processes before hand so they can be modified before enabled.
  76382. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76383. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76384. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76385. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76386. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76387. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76388. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76389. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76390. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76391. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76392. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76393. _this.bloomKernel = _this.bloomKernel;
  76394. });
  76395. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76396. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76397. });
  76398. _this._buildPipeline();
  76399. return _this;
  76400. }
  76401. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76402. get: function () {
  76403. return this._sharpenEnabled;
  76404. },
  76405. /**
  76406. * Enable or disable the sharpen process from the pipeline
  76407. */
  76408. set: function (enabled) {
  76409. if (this._sharpenEnabled === enabled) {
  76410. return;
  76411. }
  76412. this._sharpenEnabled = enabled;
  76413. this._buildPipeline();
  76414. },
  76415. enumerable: true,
  76416. configurable: true
  76417. });
  76418. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76419. /**
  76420. * Specifies the size of the bloom blur kernel, relative to the final output size
  76421. */
  76422. get: function () {
  76423. return this._bloomKernel;
  76424. },
  76425. set: function (value) {
  76426. this._bloomKernel = value;
  76427. this.bloom.kernel = value / this._hardwareScaleLevel;
  76428. },
  76429. enumerable: true,
  76430. configurable: true
  76431. });
  76432. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76433. get: function () {
  76434. return this._bloomWeight;
  76435. },
  76436. /**
  76437. * The strength of the bloom.
  76438. */
  76439. set: function (value) {
  76440. if (this._bloomWeight === value) {
  76441. return;
  76442. }
  76443. this.bloom.weight = value;
  76444. this._bloomWeight = value;
  76445. },
  76446. enumerable: true,
  76447. configurable: true
  76448. });
  76449. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76450. get: function () {
  76451. return this._bloomThreshold;
  76452. },
  76453. /**
  76454. * The strength of the bloom.
  76455. */
  76456. set: function (value) {
  76457. if (this._bloomThreshold === value) {
  76458. return;
  76459. }
  76460. this.bloom.threshold = value;
  76461. this._bloomThreshold = value;
  76462. },
  76463. enumerable: true,
  76464. configurable: true
  76465. });
  76466. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76467. get: function () {
  76468. return this._bloomScale;
  76469. },
  76470. /**
  76471. * The scale of the bloom, lower value will provide better performance.
  76472. */
  76473. set: function (value) {
  76474. if (this._bloomScale === value) {
  76475. return;
  76476. }
  76477. this._bloomScale = value;
  76478. // recreate bloom and dispose old as this setting is not dynamic
  76479. this._rebuildBloom();
  76480. this._buildPipeline();
  76481. },
  76482. enumerable: true,
  76483. configurable: true
  76484. });
  76485. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76486. get: function () {
  76487. return this._bloomEnabled;
  76488. },
  76489. /**
  76490. * Enable or disable the bloom from the pipeline
  76491. */
  76492. set: function (enabled) {
  76493. if (this._bloomEnabled === enabled) {
  76494. return;
  76495. }
  76496. this._bloomEnabled = enabled;
  76497. this._buildPipeline();
  76498. },
  76499. enumerable: true,
  76500. configurable: true
  76501. });
  76502. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76503. // recreate bloom and dispose old as this setting is not dynamic
  76504. var oldBloom = this.bloom;
  76505. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76506. this.bloom.threshold = oldBloom.threshold;
  76507. for (var i = 0; i < this._cameras.length; i++) {
  76508. oldBloom.disposeEffects(this._cameras[i]);
  76509. }
  76510. };
  76511. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76512. /**
  76513. * If the depth of field is enabled.
  76514. */
  76515. get: function () {
  76516. return this._depthOfFieldEnabled;
  76517. },
  76518. set: function (enabled) {
  76519. if (this._depthOfFieldEnabled === enabled) {
  76520. return;
  76521. }
  76522. this._depthOfFieldEnabled = enabled;
  76523. this._buildPipeline();
  76524. },
  76525. enumerable: true,
  76526. configurable: true
  76527. });
  76528. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76529. /**
  76530. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76531. */
  76532. get: function () {
  76533. return this._depthOfFieldBlurLevel;
  76534. },
  76535. set: function (value) {
  76536. if (this._depthOfFieldBlurLevel === value) {
  76537. return;
  76538. }
  76539. this._depthOfFieldBlurLevel = value;
  76540. // recreate dof and dispose old as this setting is not dynamic
  76541. var oldDof = this.depthOfField;
  76542. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76543. this.depthOfField.focalLength = oldDof.focalLength;
  76544. this.depthOfField.focusDistance = oldDof.focusDistance;
  76545. this.depthOfField.fStop = oldDof.fStop;
  76546. this.depthOfField.lensSize = oldDof.lensSize;
  76547. for (var i = 0; i < this._cameras.length; i++) {
  76548. oldDof.disposeEffects(this._cameras[i]);
  76549. }
  76550. this._buildPipeline();
  76551. },
  76552. enumerable: true,
  76553. configurable: true
  76554. });
  76555. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76556. get: function () {
  76557. return this._fxaaEnabled;
  76558. },
  76559. /**
  76560. * If the anti aliasing is enabled.
  76561. */
  76562. set: function (enabled) {
  76563. if (this._fxaaEnabled === enabled) {
  76564. return;
  76565. }
  76566. this._fxaaEnabled = enabled;
  76567. this._buildPipeline();
  76568. },
  76569. enumerable: true,
  76570. configurable: true
  76571. });
  76572. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76573. get: function () {
  76574. return this._samples;
  76575. },
  76576. /**
  76577. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76578. */
  76579. set: function (sampleCount) {
  76580. if (this._samples === sampleCount) {
  76581. return;
  76582. }
  76583. this._samples = sampleCount;
  76584. this._buildPipeline();
  76585. },
  76586. enumerable: true,
  76587. configurable: true
  76588. });
  76589. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76590. get: function () {
  76591. return this._imageProcessingEnabled;
  76592. },
  76593. /**
  76594. * If image processing is enabled.
  76595. */
  76596. set: function (enabled) {
  76597. if (this._imageProcessingEnabled === enabled) {
  76598. return;
  76599. }
  76600. this._imageProcessingEnabled = enabled;
  76601. this._buildPipeline();
  76602. },
  76603. enumerable: true,
  76604. configurable: true
  76605. });
  76606. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76607. get: function () {
  76608. return this._glowLayer == null;
  76609. },
  76610. /**
  76611. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76612. */
  76613. set: function (enabled) {
  76614. if (enabled && !this._glowLayer) {
  76615. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76616. }
  76617. else if (!enabled && this._glowLayer) {
  76618. this._glowLayer.dispose();
  76619. this._glowLayer = null;
  76620. }
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76626. get: function () {
  76627. return this._chromaticAberrationEnabled;
  76628. },
  76629. /**
  76630. * Enable or disable the chromaticAberration process from the pipeline
  76631. */
  76632. set: function (enabled) {
  76633. if (this._chromaticAberrationEnabled === enabled) {
  76634. return;
  76635. }
  76636. this._chromaticAberrationEnabled = enabled;
  76637. this._buildPipeline();
  76638. },
  76639. enumerable: true,
  76640. configurable: true
  76641. });
  76642. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76643. get: function () {
  76644. return this._grainEnabled;
  76645. },
  76646. /**
  76647. * Enable or disable the grain process from the pipeline
  76648. */
  76649. set: function (enabled) {
  76650. if (this._grainEnabled === enabled) {
  76651. return;
  76652. }
  76653. this._grainEnabled = enabled;
  76654. this._buildPipeline();
  76655. },
  76656. enumerable: true,
  76657. configurable: true
  76658. });
  76659. /**
  76660. * Force the compilation of the entire pipeline.
  76661. */
  76662. DefaultRenderingPipeline.prototype.prepare = function () {
  76663. var previousState = this._buildAllowed;
  76664. this._buildAllowed = true;
  76665. this._buildPipeline();
  76666. this._buildAllowed = previousState;
  76667. };
  76668. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76669. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76670. if (this._hasCleared) {
  76671. postProcess.autoClear = false;
  76672. }
  76673. else {
  76674. postProcess.autoClear = true;
  76675. this._scene.autoClear = false;
  76676. this._hasCleared = true;
  76677. }
  76678. if (!skipTextureSharing) {
  76679. if (this._prevPrevPostProcess) {
  76680. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76681. }
  76682. else {
  76683. postProcess.useOwnOutput();
  76684. }
  76685. if (this._prevPostProcess) {
  76686. this._prevPrevPostProcess = this._prevPostProcess;
  76687. }
  76688. this._prevPostProcess = postProcess;
  76689. }
  76690. };
  76691. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76692. var _this = this;
  76693. if (!this._buildAllowed) {
  76694. return;
  76695. }
  76696. this._scene.autoClear = true;
  76697. var engine = this._scene.getEngine();
  76698. this._disposePostProcesses();
  76699. if (this._cameras !== null) {
  76700. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76701. // get back cameras to be used to reattach pipeline
  76702. this._cameras = this._originalCameras.slice();
  76703. }
  76704. this._reset();
  76705. this._prevPostProcess = null;
  76706. this._prevPrevPostProcess = null;
  76707. this._hasCleared = false;
  76708. if (this.depthOfFieldEnabled) {
  76709. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76710. this.depthOfField.depthTexture = depthTexture;
  76711. if (!this.depthOfField._isReady()) {
  76712. this.depthOfField._updateEffects();
  76713. }
  76714. this.addEffect(this.depthOfField);
  76715. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76716. }
  76717. if (this.bloomEnabled) {
  76718. if (!this.bloom._isReady()) {
  76719. this.bloom._updateEffects();
  76720. }
  76721. this.addEffect(this.bloom);
  76722. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76723. }
  76724. if (this._imageProcessingEnabled) {
  76725. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76726. if (this._hdr) {
  76727. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76728. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76729. }
  76730. else {
  76731. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76732. }
  76733. }
  76734. if (this.sharpenEnabled) {
  76735. if (!this.sharpen.isReady()) {
  76736. this.sharpen.updateEffect();
  76737. }
  76738. this.addEffect(this._sharpenEffect);
  76739. this._setAutoClearAndTextureSharing(this.sharpen);
  76740. }
  76741. if (this.grainEnabled) {
  76742. if (!this.grain.isReady()) {
  76743. this.grain.updateEffect();
  76744. }
  76745. this.addEffect(this._grainEffect);
  76746. this._setAutoClearAndTextureSharing(this.grain);
  76747. }
  76748. if (this.chromaticAberrationEnabled) {
  76749. if (!this.chromaticAberration.isReady()) {
  76750. this.chromaticAberration.updateEffect();
  76751. }
  76752. this.addEffect(this._chromaticAberrationEffect);
  76753. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76754. }
  76755. if (this.fxaaEnabled) {
  76756. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76757. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76758. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76759. }
  76760. if (this._cameras !== null) {
  76761. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76762. }
  76763. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76764. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76765. }
  76766. };
  76767. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76768. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76769. for (var i = 0; i < this._cameras.length; i++) {
  76770. var camera = this._cameras[i];
  76771. if (this.imageProcessing) {
  76772. this.imageProcessing.dispose(camera);
  76773. }
  76774. if (this.fxaa) {
  76775. this.fxaa.dispose(camera);
  76776. }
  76777. // These are created in the constructor and should not be disposed on every pipeline change
  76778. if (disposeNonRecreated) {
  76779. if (this.sharpen) {
  76780. this.sharpen.dispose(camera);
  76781. }
  76782. if (this.depthOfField) {
  76783. this.depthOfField.disposeEffects(camera);
  76784. }
  76785. if (this.bloom) {
  76786. this.bloom.disposeEffects(camera);
  76787. }
  76788. if (this.chromaticAberration) {
  76789. this.chromaticAberration.dispose(camera);
  76790. }
  76791. if (this.grain) {
  76792. this.grain.dispose(camera);
  76793. }
  76794. if (this._glowLayer) {
  76795. this._glowLayer.dispose();
  76796. }
  76797. }
  76798. }
  76799. this.imageProcessing = null;
  76800. this.fxaa = null;
  76801. if (disposeNonRecreated) {
  76802. this.sharpen = null;
  76803. this._sharpenEffect = null;
  76804. this.depthOfField = null;
  76805. this.bloom = null;
  76806. this.chromaticAberration = null;
  76807. this._chromaticAberrationEffect = null;
  76808. this.grain = null;
  76809. this._grainEffect = null;
  76810. this._glowLayer = null;
  76811. }
  76812. };
  76813. /**
  76814. * Dispose of the pipeline and stop all post processes
  76815. */
  76816. DefaultRenderingPipeline.prototype.dispose = function () {
  76817. this._disposePostProcesses(true);
  76818. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76819. this._scene.autoClear = true;
  76820. if (this._resizeObserver) {
  76821. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76822. this._resizeObserver = null;
  76823. }
  76824. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76825. _super.prototype.dispose.call(this);
  76826. };
  76827. /**
  76828. * Serialize the rendering pipeline (Used when exporting)
  76829. * @returns the serialized object
  76830. */
  76831. DefaultRenderingPipeline.prototype.serialize = function () {
  76832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76833. serializationObject.customType = "DefaultRenderingPipeline";
  76834. return serializationObject;
  76835. };
  76836. /**
  76837. * Parse the serialized pipeline
  76838. * @param source Source pipeline.
  76839. * @param scene The scene to load the pipeline to.
  76840. * @param rootUrl The URL of the serialized pipeline.
  76841. * @returns An instantiated pipeline from the serialized object.
  76842. */
  76843. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76844. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76845. };
  76846. __decorate([
  76847. BABYLON.serialize()
  76848. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76849. __decorate([
  76850. BABYLON.serialize()
  76851. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76852. __decorate([
  76853. BABYLON.serialize()
  76854. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76855. __decorate([
  76856. BABYLON.serialize()
  76857. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76858. __decorate([
  76859. BABYLON.serialize()
  76860. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76861. __decorate([
  76862. BABYLON.serialize()
  76863. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76864. __decorate([
  76865. BABYLON.serialize()
  76866. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76867. __decorate([
  76868. BABYLON.serialize()
  76869. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76870. __decorate([
  76871. BABYLON.serialize()
  76872. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76873. __decorate([
  76874. BABYLON.serialize()
  76875. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76876. __decorate([
  76877. BABYLON.serialize()
  76878. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76879. __decorate([
  76880. BABYLON.serialize()
  76881. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76882. __decorate([
  76883. BABYLON.serialize()
  76884. ], DefaultRenderingPipeline.prototype, "samples", null);
  76885. __decorate([
  76886. BABYLON.serialize()
  76887. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76888. __decorate([
  76889. BABYLON.serialize()
  76890. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76891. __decorate([
  76892. BABYLON.serialize()
  76893. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76894. __decorate([
  76895. BABYLON.serialize()
  76896. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76897. return DefaultRenderingPipeline;
  76898. }(BABYLON.PostProcessRenderPipeline));
  76899. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76900. })(BABYLON || (BABYLON = {}));
  76901. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76902. var BABYLON;
  76903. (function (BABYLON) {
  76904. /**
  76905. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76906. */
  76907. var GeometryBufferRenderer = /** @class */ (function () {
  76908. /**
  76909. * Creates a new G Buffer for the scene
  76910. * @param scene The scene the buffer belongs to
  76911. * @param ratio How big is the buffer related to the main canvas.
  76912. */
  76913. function GeometryBufferRenderer(scene, ratio) {
  76914. if (ratio === void 0) { ratio = 1; }
  76915. this._enablePosition = false;
  76916. this._scene = scene;
  76917. this._ratio = ratio;
  76918. // Render target
  76919. this._createRenderTargets();
  76920. }
  76921. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76922. /**
  76923. * Set the render list (meshes to be rendered) used in the G buffer.
  76924. */
  76925. set: function (meshes) {
  76926. this._multiRenderTarget.renderList = meshes;
  76927. },
  76928. enumerable: true,
  76929. configurable: true
  76930. });
  76931. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76932. /**
  76933. * Gets wether or not G buffer are supported by the running hardware.
  76934. * This requires draw buffer supports
  76935. */
  76936. get: function () {
  76937. return this._multiRenderTarget.isSupported;
  76938. },
  76939. enumerable: true,
  76940. configurable: true
  76941. });
  76942. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76943. /**
  76944. * Gets wether or not position are enabled for the G buffer.
  76945. */
  76946. get: function () {
  76947. return this._enablePosition;
  76948. },
  76949. /**
  76950. * Sets wether or not position are enabled for the G buffer.
  76951. */
  76952. set: function (enable) {
  76953. this._enablePosition = enable;
  76954. this.dispose();
  76955. this._createRenderTargets();
  76956. },
  76957. enumerable: true,
  76958. configurable: true
  76959. });
  76960. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76961. /**
  76962. * Gets the scene associated with the buffer.
  76963. */
  76964. get: function () {
  76965. return this._scene;
  76966. },
  76967. enumerable: true,
  76968. configurable: true
  76969. });
  76970. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76971. /**
  76972. * Gets the ratio used by the buffer during its creation.
  76973. * How big is the buffer related to the main canvas.
  76974. */
  76975. get: function () {
  76976. return this._ratio;
  76977. },
  76978. enumerable: true,
  76979. configurable: true
  76980. });
  76981. /**
  76982. * Checks wether everything is ready to render a submesh to the G buffer.
  76983. * @param subMesh the submesh to check readiness for
  76984. * @param useInstances is the mesh drawn using instance or not
  76985. * @returns true if ready otherwise false
  76986. */
  76987. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76988. var material = subMesh.getMaterial();
  76989. if (material && material.disableDepthWrite) {
  76990. return false;
  76991. }
  76992. var defines = [];
  76993. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76994. var mesh = subMesh.getMesh();
  76995. // Alpha test
  76996. if (material && material.needAlphaTesting()) {
  76997. defines.push("#define ALPHATEST");
  76998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76999. attribs.push(BABYLON.VertexBuffer.UVKind);
  77000. defines.push("#define UV1");
  77001. }
  77002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77003. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77004. defines.push("#define UV2");
  77005. }
  77006. }
  77007. // Buffers
  77008. if (this._enablePosition) {
  77009. defines.push("#define POSITION");
  77010. }
  77011. // Bones
  77012. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77015. if (mesh.numBoneInfluencers > 4) {
  77016. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77017. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77018. }
  77019. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77020. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77021. }
  77022. else {
  77023. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77024. }
  77025. // Instances
  77026. if (useInstances) {
  77027. defines.push("#define INSTANCES");
  77028. attribs.push("world0");
  77029. attribs.push("world1");
  77030. attribs.push("world2");
  77031. attribs.push("world3");
  77032. }
  77033. // Get correct effect
  77034. var join = defines.join("\n");
  77035. if (this._cachedDefines !== join) {
  77036. this._cachedDefines = join;
  77037. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77038. }
  77039. return this._effect.isReady();
  77040. };
  77041. /**
  77042. * Gets the current underlying G Buffer.
  77043. * @returns the buffer
  77044. */
  77045. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77046. return this._multiRenderTarget;
  77047. };
  77048. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77049. /**
  77050. * Gets the number of samples used to render the buffer (anti aliasing).
  77051. */
  77052. get: function () {
  77053. return this._multiRenderTarget.samples;
  77054. },
  77055. /**
  77056. * Sets the number of samples used to render the buffer (anti aliasing).
  77057. */
  77058. set: function (value) {
  77059. this._multiRenderTarget.samples = value;
  77060. },
  77061. enumerable: true,
  77062. configurable: true
  77063. });
  77064. /**
  77065. * Disposes the renderer and frees up associated resources.
  77066. */
  77067. GeometryBufferRenderer.prototype.dispose = function () {
  77068. this.getGBuffer().dispose();
  77069. };
  77070. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77071. var _this = this;
  77072. var engine = this._scene.getEngine();
  77073. var count = this._enablePosition ? 3 : 2;
  77074. 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 });
  77075. if (!this.isSupported) {
  77076. return;
  77077. }
  77078. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77079. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77080. this._multiRenderTarget.refreshRate = 1;
  77081. this._multiRenderTarget.renderParticles = false;
  77082. this._multiRenderTarget.renderList = null;
  77083. // set default depth value to 1.0 (far away)
  77084. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77085. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77086. });
  77087. // Custom render function
  77088. var renderSubMesh = function (subMesh) {
  77089. var mesh = subMesh.getRenderingMesh();
  77090. var scene = _this._scene;
  77091. var engine = scene.getEngine();
  77092. var material = subMesh.getMaterial();
  77093. if (!material) {
  77094. return;
  77095. }
  77096. // Culling
  77097. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77098. // Managing instances
  77099. var batch = mesh._getInstancesRenderList(subMesh._id);
  77100. if (batch.mustReturn) {
  77101. return;
  77102. }
  77103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77104. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77105. engine.enableEffect(_this._effect);
  77106. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77107. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77108. _this._effect.setMatrix("view", scene.getViewMatrix());
  77109. // Alpha test
  77110. if (material && material.needAlphaTesting()) {
  77111. var alphaTexture = material.getAlphaTestTexture();
  77112. if (alphaTexture) {
  77113. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77114. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77115. }
  77116. }
  77117. // Bones
  77118. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77119. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77120. }
  77121. // Draw
  77122. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77123. }
  77124. };
  77125. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77126. var index;
  77127. if (depthOnlySubMeshes.length) {
  77128. engine.setColorWrite(false);
  77129. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77130. renderSubMesh(depthOnlySubMeshes.data[index]);
  77131. }
  77132. engine.setColorWrite(true);
  77133. }
  77134. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77135. renderSubMesh(opaqueSubMeshes.data[index]);
  77136. }
  77137. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77138. renderSubMesh(alphaTestSubMeshes.data[index]);
  77139. }
  77140. };
  77141. };
  77142. return GeometryBufferRenderer;
  77143. }());
  77144. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77145. })(BABYLON || (BABYLON = {}));
  77146. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77147. var BABYLON;
  77148. (function (BABYLON) {
  77149. var RefractionPostProcess = /** @class */ (function (_super) {
  77150. __extends(RefractionPostProcess, _super);
  77151. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77152. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77153. _this.color = color;
  77154. _this.depth = depth;
  77155. _this.colorLevel = colorLevel;
  77156. _this._ownRefractionTexture = true;
  77157. _this.onActivateObservable.add(function (cam) {
  77158. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77159. });
  77160. _this.onApplyObservable.add(function (effect) {
  77161. effect.setColor3("baseColor", _this.color);
  77162. effect.setFloat("depth", _this.depth);
  77163. effect.setFloat("colorLevel", _this.colorLevel);
  77164. effect.setTexture("refractionSampler", _this._refTexture);
  77165. });
  77166. return _this;
  77167. }
  77168. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77169. /**
  77170. * Gets or sets the refraction texture
  77171. * Please note that you are responsible for disposing the texture if you set it manually
  77172. */
  77173. get: function () {
  77174. return this._refTexture;
  77175. },
  77176. set: function (value) {
  77177. if (this._refTexture && this._ownRefractionTexture) {
  77178. this._refTexture.dispose();
  77179. }
  77180. this._refTexture = value;
  77181. this._ownRefractionTexture = false;
  77182. },
  77183. enumerable: true,
  77184. configurable: true
  77185. });
  77186. // Methods
  77187. RefractionPostProcess.prototype.dispose = function (camera) {
  77188. if (this._refTexture && this._ownRefractionTexture) {
  77189. this._refTexture.dispose();
  77190. this._refTexture = null;
  77191. }
  77192. _super.prototype.dispose.call(this, camera);
  77193. };
  77194. return RefractionPostProcess;
  77195. }(BABYLON.PostProcess));
  77196. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77197. })(BABYLON || (BABYLON = {}));
  77198. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77199. var BABYLON;
  77200. (function (BABYLON) {
  77201. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77202. __extends(BlackAndWhitePostProcess, _super);
  77203. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77204. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77205. _this.degree = 1;
  77206. _this.onApplyObservable.add(function (effect) {
  77207. effect.setFloat("degree", _this.degree);
  77208. });
  77209. return _this;
  77210. }
  77211. return BlackAndWhitePostProcess;
  77212. }(BABYLON.PostProcess));
  77213. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77214. })(BABYLON || (BABYLON = {}));
  77215. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77216. var BABYLON;
  77217. (function (BABYLON) {
  77218. /**
  77219. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77220. * input texture to perform effects such as edge detection or sharpening
  77221. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77222. */
  77223. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77224. __extends(ConvolutionPostProcess, _super);
  77225. /**
  77226. * Creates a new instance ConvolutionPostProcess
  77227. * @param name The name of the effect.
  77228. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77229. * @param options The required width/height ratio to downsize to before computing the render pass.
  77230. * @param camera The camera to apply the render pass to.
  77231. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77232. * @param engine The engine which the post process will be applied. (default: current engine)
  77233. * @param reusable If the post process can be reused on the same frame. (default: false)
  77234. * @param textureType Type of textures used when performing the post process. (default: 0)
  77235. */
  77236. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77237. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77238. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77239. _this.kernel = kernel;
  77240. _this.onApply = function (effect) {
  77241. effect.setFloat2("screenSize", _this.width, _this.height);
  77242. effect.setArray("kernel", _this.kernel);
  77243. };
  77244. return _this;
  77245. }
  77246. // Statics
  77247. /**
  77248. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77249. */
  77250. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77251. /**
  77252. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77253. */
  77254. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77255. /**
  77256. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77257. */
  77258. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77259. /**
  77260. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77261. */
  77262. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77263. /**
  77264. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77265. */
  77266. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77267. /**
  77268. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77269. */
  77270. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77271. return ConvolutionPostProcess;
  77272. }(BABYLON.PostProcess));
  77273. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77274. })(BABYLON || (BABYLON = {}));
  77275. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77276. var BABYLON;
  77277. (function (BABYLON) {
  77278. var FilterPostProcess = /** @class */ (function (_super) {
  77279. __extends(FilterPostProcess, _super);
  77280. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77281. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77282. _this.kernelMatrix = kernelMatrix;
  77283. _this.onApply = function (effect) {
  77284. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77285. };
  77286. return _this;
  77287. }
  77288. return FilterPostProcess;
  77289. }(BABYLON.PostProcess));
  77290. BABYLON.FilterPostProcess = FilterPostProcess;
  77291. })(BABYLON || (BABYLON = {}));
  77292. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77293. var BABYLON;
  77294. (function (BABYLON) {
  77295. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77296. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77297. __extends(VolumetricLightScatteringPostProcess, _super);
  77298. /**
  77299. * @constructor
  77300. * @param {string} name - The post-process name
  77301. * @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)
  77302. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77303. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77304. * @param {number} samples - The post-process quality, default 100
  77305. * @param {number} samplingMode - The post-process filtering mode
  77306. * @param {BABYLON.Engine} engine - The babylon engine
  77307. * @param {boolean} reusable - If the post-process is reusable
  77308. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77309. */
  77310. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77311. if (samples === void 0) { samples = 100; }
  77312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77313. 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;
  77314. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77315. /**
  77316. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77317. */
  77318. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77319. /**
  77320. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77321. */
  77322. _this.useCustomMeshPosition = false;
  77323. /**
  77324. * If the post-process should inverse the light scattering direction
  77325. */
  77326. _this.invert = true;
  77327. /**
  77328. * Array containing the excluded meshes not rendered in the internal pass
  77329. */
  77330. _this.excludedMeshes = new Array();
  77331. /**
  77332. * Controls the overall intensity of the post-process
  77333. */
  77334. _this.exposure = 0.3;
  77335. /**
  77336. * Dissipates each sample's contribution in range [0, 1]
  77337. */
  77338. _this.decay = 0.96815;
  77339. /**
  77340. * Controls the overall intensity of each sample
  77341. */
  77342. _this.weight = 0.58767;
  77343. /**
  77344. * Controls the density of each sample
  77345. */
  77346. _this.density = 0.926;
  77347. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77348. engine = scene.getEngine();
  77349. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77350. // Configure mesh
  77351. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77352. // Configure
  77353. _this._createPass(scene, ratio.passRatio || ratio);
  77354. _this.onActivate = function (camera) {
  77355. if (!_this.isSupported) {
  77356. _this.dispose(camera);
  77357. }
  77358. _this.onActivate = null;
  77359. };
  77360. _this.onApplyObservable.add(function (effect) {
  77361. _this._updateMeshScreenCoordinates(scene);
  77362. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77363. effect.setFloat("exposure", _this.exposure);
  77364. effect.setFloat("decay", _this.decay);
  77365. effect.setFloat("weight", _this.weight);
  77366. effect.setFloat("density", _this.density);
  77367. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77368. });
  77369. return _this;
  77370. }
  77371. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77372. get: function () {
  77373. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77374. return false;
  77375. },
  77376. set: function (useDiffuseColor) {
  77377. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77378. },
  77379. enumerable: true,
  77380. configurable: true
  77381. });
  77382. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77383. return "VolumetricLightScatteringPostProcess";
  77384. };
  77385. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77386. var mesh = subMesh.getMesh();
  77387. // Render this.mesh as default
  77388. if (mesh === this.mesh && mesh.material) {
  77389. return mesh.material.isReady(mesh);
  77390. }
  77391. var defines = [];
  77392. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77393. var material = subMesh.getMaterial();
  77394. // Alpha test
  77395. if (material) {
  77396. if (material.needAlphaTesting()) {
  77397. defines.push("#define ALPHATEST");
  77398. }
  77399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77400. attribs.push(BABYLON.VertexBuffer.UVKind);
  77401. defines.push("#define UV1");
  77402. }
  77403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77404. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77405. defines.push("#define UV2");
  77406. }
  77407. }
  77408. // Bones
  77409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77412. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77413. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77414. }
  77415. else {
  77416. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77417. }
  77418. // Instances
  77419. if (useInstances) {
  77420. defines.push("#define INSTANCES");
  77421. attribs.push("world0");
  77422. attribs.push("world1");
  77423. attribs.push("world2");
  77424. attribs.push("world3");
  77425. }
  77426. // Get correct effect
  77427. var join = defines.join("\n");
  77428. if (this._cachedDefines !== join) {
  77429. this._cachedDefines = join;
  77430. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77431. }
  77432. return this._volumetricLightScatteringPass.isReady();
  77433. };
  77434. /**
  77435. * Sets the new light position for light scattering effect
  77436. * @param {BABYLON.Vector3} The new custom light position
  77437. */
  77438. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77439. this.customMeshPosition = position;
  77440. };
  77441. /**
  77442. * Returns the light position for light scattering effect
  77443. * @return {BABYLON.Vector3} The custom light position
  77444. */
  77445. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77446. return this.customMeshPosition;
  77447. };
  77448. /**
  77449. * Disposes the internal assets and detaches the post-process from the camera
  77450. */
  77451. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77452. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77453. if (rttIndex !== -1) {
  77454. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77455. }
  77456. this._volumetricLightScatteringRTT.dispose();
  77457. _super.prototype.dispose.call(this, camera);
  77458. };
  77459. /**
  77460. * Returns the render target texture used by the post-process
  77461. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77462. */
  77463. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77464. return this._volumetricLightScatteringRTT;
  77465. };
  77466. // Private methods
  77467. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77468. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77469. return true;
  77470. }
  77471. return false;
  77472. };
  77473. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77474. var _this = this;
  77475. var engine = scene.getEngine();
  77476. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77477. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77478. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77479. this._volumetricLightScatteringRTT.renderList = null;
  77480. this._volumetricLightScatteringRTT.renderParticles = false;
  77481. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77482. var camera = this.getCamera();
  77483. if (camera) {
  77484. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77485. }
  77486. else {
  77487. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77488. }
  77489. // Custom render function for submeshes
  77490. var renderSubMesh = function (subMesh) {
  77491. var mesh = subMesh.getRenderingMesh();
  77492. if (_this._meshExcluded(mesh)) {
  77493. return;
  77494. }
  77495. var material = subMesh.getMaterial();
  77496. if (!material) {
  77497. return;
  77498. }
  77499. var scene = mesh.getScene();
  77500. var engine = scene.getEngine();
  77501. // Culling
  77502. engine.setState(material.backFaceCulling);
  77503. // Managing instances
  77504. var batch = mesh._getInstancesRenderList(subMesh._id);
  77505. if (batch.mustReturn) {
  77506. return;
  77507. }
  77508. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77509. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77510. var effect = _this._volumetricLightScatteringPass;
  77511. if (mesh === _this.mesh) {
  77512. if (subMesh.effect) {
  77513. effect = subMesh.effect;
  77514. }
  77515. else {
  77516. effect = material.getEffect();
  77517. }
  77518. }
  77519. engine.enableEffect(effect);
  77520. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77521. if (mesh === _this.mesh) {
  77522. material.bind(mesh.getWorldMatrix(), mesh);
  77523. }
  77524. else {
  77525. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77526. // Alpha test
  77527. if (material && material.needAlphaTesting()) {
  77528. var alphaTexture = material.getAlphaTestTexture();
  77529. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77530. if (alphaTexture) {
  77531. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77532. }
  77533. }
  77534. // Bones
  77535. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77536. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77537. }
  77538. }
  77539. // Draw
  77540. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77541. }
  77542. };
  77543. // Render target texture callbacks
  77544. var savedSceneClearColor;
  77545. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77546. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77547. savedSceneClearColor = scene.clearColor;
  77548. scene.clearColor = sceneClearColor;
  77549. });
  77550. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77551. scene.clearColor = savedSceneClearColor;
  77552. });
  77553. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77554. var engine = scene.getEngine();
  77555. var index;
  77556. if (depthOnlySubMeshes.length) {
  77557. engine.setColorWrite(false);
  77558. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77559. renderSubMesh(depthOnlySubMeshes.data[index]);
  77560. }
  77561. engine.setColorWrite(true);
  77562. }
  77563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77564. renderSubMesh(opaqueSubMeshes.data[index]);
  77565. }
  77566. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77567. renderSubMesh(alphaTestSubMeshes.data[index]);
  77568. }
  77569. if (transparentSubMeshes.length) {
  77570. // Sort sub meshes
  77571. for (index = 0; index < transparentSubMeshes.length; index++) {
  77572. var submesh = transparentSubMeshes.data[index];
  77573. var boundingInfo = submesh.getBoundingInfo();
  77574. if (boundingInfo && scene.activeCamera) {
  77575. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77576. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77577. }
  77578. }
  77579. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77580. sortedArray.sort(function (a, b) {
  77581. // Alpha index first
  77582. if (a._alphaIndex > b._alphaIndex) {
  77583. return 1;
  77584. }
  77585. if (a._alphaIndex < b._alphaIndex) {
  77586. return -1;
  77587. }
  77588. // Then distance to camera
  77589. if (a._distanceToCamera < b._distanceToCamera) {
  77590. return 1;
  77591. }
  77592. if (a._distanceToCamera > b._distanceToCamera) {
  77593. return -1;
  77594. }
  77595. return 0;
  77596. });
  77597. // Render sub meshes
  77598. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77599. for (index = 0; index < sortedArray.length; index++) {
  77600. renderSubMesh(sortedArray[index]);
  77601. }
  77602. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77603. }
  77604. };
  77605. };
  77606. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77607. var transform = scene.getTransformMatrix();
  77608. var meshPosition;
  77609. if (this.useCustomMeshPosition) {
  77610. meshPosition = this.customMeshPosition;
  77611. }
  77612. else if (this.attachedNode) {
  77613. meshPosition = this.attachedNode.position;
  77614. }
  77615. else {
  77616. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77617. }
  77618. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77619. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77620. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77621. if (this.invert)
  77622. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77623. };
  77624. // Static methods
  77625. /**
  77626. * Creates a default mesh for the Volumeric Light Scattering post-process
  77627. * @param {string} The mesh name
  77628. * @param {BABYLON.Scene} The scene where to create the mesh
  77629. * @return {BABYLON.Mesh} the default mesh
  77630. */
  77631. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77632. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77633. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77634. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77635. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77636. mesh.material = material;
  77637. return mesh;
  77638. };
  77639. __decorate([
  77640. BABYLON.serializeAsVector3()
  77641. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77642. __decorate([
  77643. BABYLON.serialize()
  77644. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77645. __decorate([
  77646. BABYLON.serialize()
  77647. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77648. __decorate([
  77649. BABYLON.serializeAsMeshReference()
  77650. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77651. __decorate([
  77652. BABYLON.serialize()
  77653. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77654. __decorate([
  77655. BABYLON.serialize()
  77656. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77657. __decorate([
  77658. BABYLON.serialize()
  77659. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77660. __decorate([
  77661. BABYLON.serialize()
  77662. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77663. __decorate([
  77664. BABYLON.serialize()
  77665. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77666. return VolumetricLightScatteringPostProcess;
  77667. }(BABYLON.PostProcess));
  77668. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77669. })(BABYLON || (BABYLON = {}));
  77670. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77671. //
  77672. // This post-process allows the modification of rendered colors by using
  77673. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77674. //
  77675. // The object needs to be provided an url to a texture containing the color
  77676. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77677. // Use an image editing software to tweak the LUT to match your needs.
  77678. //
  77679. // For an example of a color LUT, see here:
  77680. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77681. // For explanations on color grading, see here:
  77682. // http://udn.epicgames.com/Three/ColorGrading.html
  77683. //
  77684. var BABYLON;
  77685. (function (BABYLON) {
  77686. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77687. __extends(ColorCorrectionPostProcess, _super);
  77688. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77689. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77690. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77691. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77692. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77693. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77694. _this.onApply = function (effect) {
  77695. effect.setTexture("colorTable", _this._colorTableTexture);
  77696. };
  77697. return _this;
  77698. }
  77699. return ColorCorrectionPostProcess;
  77700. }(BABYLON.PostProcess));
  77701. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77702. })(BABYLON || (BABYLON = {}));
  77703. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77704. var BABYLON;
  77705. (function (BABYLON) {
  77706. /** Defines operator used for tonemapping */
  77707. var TonemappingOperator;
  77708. (function (TonemappingOperator) {
  77709. /** Hable */
  77710. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77711. /** Reinhard */
  77712. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77713. /** HejiDawson */
  77714. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77715. /** Photographic */
  77716. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77717. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77718. ;
  77719. /**
  77720. * Defines a post process to apply tone mapping
  77721. */
  77722. var TonemapPostProcess = /** @class */ (function (_super) {
  77723. __extends(TonemapPostProcess, _super);
  77724. /**
  77725. * Creates a new TonemapPostProcess
  77726. * @param name defines the name of the postprocess
  77727. * @param _operator defines the operator to use
  77728. * @param exposureAdjustment defines the required exposure adjustement
  77729. * @param camera defines the camera to use (can be null)
  77730. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77731. * @param engine defines the hosting engine (can be ignore if camera is set)
  77732. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77733. */
  77734. function TonemapPostProcess(name, _operator,
  77735. /** Defines the required exposure adjustement */
  77736. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77738. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77739. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77740. _this._operator = _operator;
  77741. _this.exposureAdjustment = exposureAdjustment;
  77742. var defines = "#define ";
  77743. if (_this._operator === TonemappingOperator.Hable)
  77744. defines += "HABLE_TONEMAPPING";
  77745. else if (_this._operator === TonemappingOperator.Reinhard)
  77746. defines += "REINHARD_TONEMAPPING";
  77747. else if (_this._operator === TonemappingOperator.HejiDawson)
  77748. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77749. else if (_this._operator === TonemappingOperator.Photographic)
  77750. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77751. //sadly a second call to create the effect.
  77752. _this.updateEffect(defines);
  77753. _this.onApply = function (effect) {
  77754. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77755. };
  77756. return _this;
  77757. }
  77758. return TonemapPostProcess;
  77759. }(BABYLON.PostProcess));
  77760. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77761. })(BABYLON || (BABYLON = {}));
  77762. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77763. var BABYLON;
  77764. (function (BABYLON) {
  77765. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77766. __extends(DisplayPassPostProcess, _super);
  77767. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77768. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77769. }
  77770. return DisplayPassPostProcess;
  77771. }(BABYLON.PostProcess));
  77772. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77773. })(BABYLON || (BABYLON = {}));
  77774. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77775. var BABYLON;
  77776. (function (BABYLON) {
  77777. var HighlightsPostProcess = /** @class */ (function (_super) {
  77778. __extends(HighlightsPostProcess, _super);
  77779. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77780. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77781. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77782. }
  77783. return HighlightsPostProcess;
  77784. }(BABYLON.PostProcess));
  77785. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77786. })(BABYLON || (BABYLON = {}));
  77787. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77788. var BABYLON;
  77789. (function (BABYLON) {
  77790. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77791. __extends(ImageProcessingPostProcess, _super);
  77792. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77793. if (camera === void 0) { camera = null; }
  77794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77795. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77796. _this._fromLinearSpace = true;
  77797. /**
  77798. * Defines cache preventing GC.
  77799. */
  77800. _this._defines = {
  77801. IMAGEPROCESSING: false,
  77802. VIGNETTE: false,
  77803. VIGNETTEBLENDMODEMULTIPLY: false,
  77804. VIGNETTEBLENDMODEOPAQUE: false,
  77805. TONEMAPPING: false,
  77806. CONTRAST: false,
  77807. COLORCURVES: false,
  77808. COLORGRADING: false,
  77809. COLORGRADING3D: false,
  77810. FROMLINEARSPACE: false,
  77811. SAMPLER3DGREENDEPTH: false,
  77812. SAMPLER3DBGRMAP: false,
  77813. IMAGEPROCESSINGPOSTPROCESS: false,
  77814. EXPOSURE: false,
  77815. };
  77816. // Setup the configuration as forced by the constructor. This would then not force the
  77817. // scene materials output in linear space and let untouched the default forward pass.
  77818. if (imageProcessingConfiguration) {
  77819. imageProcessingConfiguration.applyByPostProcess = true;
  77820. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77821. // This will cause the shader to be compiled
  77822. _this.fromLinearSpace = false;
  77823. }
  77824. // Setup the default processing configuration to the scene.
  77825. else {
  77826. _this._attachImageProcessingConfiguration(null, true);
  77827. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77828. }
  77829. _this.onApply = function (effect) {
  77830. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77831. };
  77832. return _this;
  77833. }
  77834. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77835. /**
  77836. * Gets the image processing configuration used either in this material.
  77837. */
  77838. get: function () {
  77839. return this._imageProcessingConfiguration;
  77840. },
  77841. /**
  77842. * Sets the Default image processing configuration used either in the this material.
  77843. *
  77844. * If sets to null, the scene one is in use.
  77845. */
  77846. set: function (value) {
  77847. this._attachImageProcessingConfiguration(value);
  77848. },
  77849. enumerable: true,
  77850. configurable: true
  77851. });
  77852. /**
  77853. * Attaches a new image processing configuration to the PBR Material.
  77854. * @param configuration
  77855. */
  77856. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77857. var _this = this;
  77858. if (doNotBuild === void 0) { doNotBuild = false; }
  77859. if (configuration === this._imageProcessingConfiguration) {
  77860. return;
  77861. }
  77862. // Detaches observer.
  77863. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77864. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77865. }
  77866. // Pick the scene configuration if needed.
  77867. if (!configuration) {
  77868. var scene = null;
  77869. var engine = this.getEngine();
  77870. var camera = this.getCamera();
  77871. if (camera) {
  77872. scene = camera.getScene();
  77873. }
  77874. else if (engine && engine.scenes) {
  77875. var scenes = engine.scenes;
  77876. scene = scenes[scenes.length - 1];
  77877. }
  77878. else {
  77879. scene = BABYLON.Engine.LastCreatedScene;
  77880. }
  77881. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77882. }
  77883. else {
  77884. this._imageProcessingConfiguration = configuration;
  77885. }
  77886. // Attaches observer.
  77887. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77888. _this._updateParameters();
  77889. });
  77890. // Ensure the effect will be rebuilt.
  77891. if (!doNotBuild) {
  77892. this._updateParameters();
  77893. }
  77894. };
  77895. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77896. /**
  77897. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77898. */
  77899. get: function () {
  77900. return this.imageProcessingConfiguration.colorCurves;
  77901. },
  77902. /**
  77903. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77904. */
  77905. set: function (value) {
  77906. this.imageProcessingConfiguration.colorCurves = value;
  77907. },
  77908. enumerable: true,
  77909. configurable: true
  77910. });
  77911. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77912. /**
  77913. * Gets wether the color curves effect is enabled.
  77914. */
  77915. get: function () {
  77916. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77917. },
  77918. /**
  77919. * Sets wether the color curves effect is enabled.
  77920. */
  77921. set: function (value) {
  77922. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77923. },
  77924. enumerable: true,
  77925. configurable: true
  77926. });
  77927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77928. /**
  77929. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77930. */
  77931. get: function () {
  77932. return this.imageProcessingConfiguration.colorGradingTexture;
  77933. },
  77934. /**
  77935. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77936. */
  77937. set: function (value) {
  77938. this.imageProcessingConfiguration.colorGradingTexture = value;
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77944. /**
  77945. * Gets wether the color grading effect is enabled.
  77946. */
  77947. get: function () {
  77948. return this.imageProcessingConfiguration.colorGradingEnabled;
  77949. },
  77950. /**
  77951. * Gets wether the color grading effect is enabled.
  77952. */
  77953. set: function (value) {
  77954. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77955. },
  77956. enumerable: true,
  77957. configurable: true
  77958. });
  77959. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77960. /**
  77961. * Gets exposure used in the effect.
  77962. */
  77963. get: function () {
  77964. return this.imageProcessingConfiguration.exposure;
  77965. },
  77966. /**
  77967. * Sets exposure used in the effect.
  77968. */
  77969. set: function (value) {
  77970. this.imageProcessingConfiguration.exposure = value;
  77971. },
  77972. enumerable: true,
  77973. configurable: true
  77974. });
  77975. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77976. /**
  77977. * Gets wether tonemapping is enabled or not.
  77978. */
  77979. get: function () {
  77980. return this._imageProcessingConfiguration.toneMappingEnabled;
  77981. },
  77982. /**
  77983. * Sets wether tonemapping is enabled or not
  77984. */
  77985. set: function (value) {
  77986. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77987. },
  77988. enumerable: true,
  77989. configurable: true
  77990. });
  77991. ;
  77992. ;
  77993. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77994. /**
  77995. * Gets contrast used in the effect.
  77996. */
  77997. get: function () {
  77998. return this.imageProcessingConfiguration.contrast;
  77999. },
  78000. /**
  78001. * Sets contrast used in the effect.
  78002. */
  78003. set: function (value) {
  78004. this.imageProcessingConfiguration.contrast = value;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78010. /**
  78011. * Gets Vignette stretch size.
  78012. */
  78013. get: function () {
  78014. return this.imageProcessingConfiguration.vignetteStretch;
  78015. },
  78016. /**
  78017. * Sets Vignette stretch size.
  78018. */
  78019. set: function (value) {
  78020. this.imageProcessingConfiguration.vignetteStretch = value;
  78021. },
  78022. enumerable: true,
  78023. configurable: true
  78024. });
  78025. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78026. /**
  78027. * Gets Vignette centre X Offset.
  78028. */
  78029. get: function () {
  78030. return this.imageProcessingConfiguration.vignetteCentreX;
  78031. },
  78032. /**
  78033. * Sets Vignette centre X Offset.
  78034. */
  78035. set: function (value) {
  78036. this.imageProcessingConfiguration.vignetteCentreX = value;
  78037. },
  78038. enumerable: true,
  78039. configurable: true
  78040. });
  78041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78042. /**
  78043. * Gets Vignette centre Y Offset.
  78044. */
  78045. get: function () {
  78046. return this.imageProcessingConfiguration.vignetteCentreY;
  78047. },
  78048. /**
  78049. * Sets Vignette centre Y Offset.
  78050. */
  78051. set: function (value) {
  78052. this.imageProcessingConfiguration.vignetteCentreY = value;
  78053. },
  78054. enumerable: true,
  78055. configurable: true
  78056. });
  78057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78058. /**
  78059. * Gets Vignette weight or intensity of the vignette effect.
  78060. */
  78061. get: function () {
  78062. return this.imageProcessingConfiguration.vignetteWeight;
  78063. },
  78064. /**
  78065. * Sets Vignette weight or intensity of the vignette effect.
  78066. */
  78067. set: function (value) {
  78068. this.imageProcessingConfiguration.vignetteWeight = value;
  78069. },
  78070. enumerable: true,
  78071. configurable: true
  78072. });
  78073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78074. /**
  78075. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78076. * if vignetteEnabled is set to true.
  78077. */
  78078. get: function () {
  78079. return this.imageProcessingConfiguration.vignetteColor;
  78080. },
  78081. /**
  78082. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78083. * if vignetteEnabled is set to true.
  78084. */
  78085. set: function (value) {
  78086. this.imageProcessingConfiguration.vignetteColor = value;
  78087. },
  78088. enumerable: true,
  78089. configurable: true
  78090. });
  78091. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78092. /**
  78093. * Gets Camera field of view used by the Vignette effect.
  78094. */
  78095. get: function () {
  78096. return this.imageProcessingConfiguration.vignetteCameraFov;
  78097. },
  78098. /**
  78099. * Sets Camera field of view used by the Vignette effect.
  78100. */
  78101. set: function (value) {
  78102. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78103. },
  78104. enumerable: true,
  78105. configurable: true
  78106. });
  78107. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78108. /**
  78109. * Gets the vignette blend mode allowing different kind of effect.
  78110. */
  78111. get: function () {
  78112. return this.imageProcessingConfiguration.vignetteBlendMode;
  78113. },
  78114. /**
  78115. * Sets the vignette blend mode allowing different kind of effect.
  78116. */
  78117. set: function (value) {
  78118. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78119. },
  78120. enumerable: true,
  78121. configurable: true
  78122. });
  78123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78124. /**
  78125. * Gets wether the vignette effect is enabled.
  78126. */
  78127. get: function () {
  78128. return this.imageProcessingConfiguration.vignetteEnabled;
  78129. },
  78130. /**
  78131. * Sets wether the vignette effect is enabled.
  78132. */
  78133. set: function (value) {
  78134. this.imageProcessingConfiguration.vignetteEnabled = value;
  78135. },
  78136. enumerable: true,
  78137. configurable: true
  78138. });
  78139. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78140. /**
  78141. * Gets wether the input of the processing is in Gamma or Linear Space.
  78142. */
  78143. get: function () {
  78144. return this._fromLinearSpace;
  78145. },
  78146. /**
  78147. * Sets wether the input of the processing is in Gamma or Linear Space.
  78148. */
  78149. set: function (value) {
  78150. if (this._fromLinearSpace === value) {
  78151. return;
  78152. }
  78153. this._fromLinearSpace = value;
  78154. this._updateParameters();
  78155. },
  78156. enumerable: true,
  78157. configurable: true
  78158. });
  78159. ImageProcessingPostProcess.prototype.getClassName = function () {
  78160. return "ImageProcessingPostProcess";
  78161. };
  78162. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78163. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78164. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78165. var defines = "";
  78166. for (var define in this._defines) {
  78167. if (this._defines[define]) {
  78168. defines += "#define " + define + ";\r\n";
  78169. }
  78170. }
  78171. var samplers = ["textureSampler"];
  78172. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78173. var uniforms = ["scale"];
  78174. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78175. this.updateEffect(defines, uniforms, samplers);
  78176. };
  78177. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78178. _super.prototype.dispose.call(this, camera);
  78179. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78180. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78181. }
  78182. this.imageProcessingConfiguration.applyByPostProcess = false;
  78183. };
  78184. __decorate([
  78185. BABYLON.serialize()
  78186. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78187. return ImageProcessingPostProcess;
  78188. }(BABYLON.PostProcess));
  78189. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78190. })(BABYLON || (BABYLON = {}));
  78191. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78192. var BABYLON;
  78193. (function (BABYLON) {
  78194. /**
  78195. * Class used to store bone information
  78196. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78197. */
  78198. var Bone = /** @class */ (function (_super) {
  78199. __extends(Bone, _super);
  78200. /**
  78201. * Create a new bone
  78202. * @param name defines the bone name
  78203. * @param skeleton defines the parent skeleton
  78204. * @param parentBone defines the parent (can be null if the bone is the root)
  78205. * @param localMatrix defines the local matrix
  78206. * @param restPose defines the rest pose matrix
  78207. * @param baseMatrix defines the base matrix
  78208. * @param index defines index of the bone in the hiearchy
  78209. */
  78210. function Bone(
  78211. /**
  78212. * defines the bone name
  78213. */
  78214. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78215. if (parentBone === void 0) { parentBone = null; }
  78216. if (localMatrix === void 0) { localMatrix = null; }
  78217. if (restPose === void 0) { restPose = null; }
  78218. if (baseMatrix === void 0) { baseMatrix = null; }
  78219. if (index === void 0) { index = null; }
  78220. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78221. _this.name = name;
  78222. /**
  78223. * Gets the list of child bones
  78224. */
  78225. _this.children = new Array();
  78226. /** Gets the animations associated with this bone */
  78227. _this.animations = new Array();
  78228. /**
  78229. * @hidden Internal only
  78230. * Set this value to map this bone to a different index in the transform matrices
  78231. * Set this value to -1 to exclude the bone from the transform matrices
  78232. */
  78233. _this._index = null;
  78234. _this._absoluteTransform = new BABYLON.Matrix();
  78235. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78236. _this._scalingDeterminant = 1;
  78237. _this._worldTransform = new BABYLON.Matrix();
  78238. _this._needToDecompose = true;
  78239. _this._needToCompose = false;
  78240. _this._skeleton = skeleton;
  78241. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78242. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78243. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78244. _this._index = index;
  78245. skeleton.bones.push(_this);
  78246. _this.setParent(parentBone, false);
  78247. if (baseMatrix || localMatrix) {
  78248. _this._updateDifferenceMatrix();
  78249. }
  78250. return _this;
  78251. }
  78252. Object.defineProperty(Bone.prototype, "_matrix", {
  78253. /** @hidden */
  78254. get: function () {
  78255. this._compose();
  78256. return this._localMatrix;
  78257. },
  78258. /** @hidden */
  78259. set: function (value) {
  78260. this._localMatrix.copyFrom(value);
  78261. this._needToDecompose = true;
  78262. },
  78263. enumerable: true,
  78264. configurable: true
  78265. });
  78266. // Members
  78267. /**
  78268. * Gets the parent skeleton
  78269. * @returns a skeleton
  78270. */
  78271. Bone.prototype.getSkeleton = function () {
  78272. return this._skeleton;
  78273. };
  78274. /**
  78275. * Gets parent bone
  78276. * @returns a bone or null if the bone is the root of the bone hierarchy
  78277. */
  78278. Bone.prototype.getParent = function () {
  78279. return this._parent;
  78280. };
  78281. /**
  78282. * Sets the parent bone
  78283. * @param parent defines the parent (can be null if the bone is the root)
  78284. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78285. */
  78286. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78287. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78288. if (this._parent === parent) {
  78289. return;
  78290. }
  78291. if (this._parent) {
  78292. var index = this._parent.children.indexOf(this);
  78293. if (index !== -1) {
  78294. this._parent.children.splice(index, 1);
  78295. }
  78296. }
  78297. this._parent = parent;
  78298. if (this._parent) {
  78299. this._parent.children.push(this);
  78300. }
  78301. if (updateDifferenceMatrix) {
  78302. this._updateDifferenceMatrix();
  78303. }
  78304. this.markAsDirty();
  78305. };
  78306. /**
  78307. * Gets the local matrix
  78308. * @returns a matrix
  78309. */
  78310. Bone.prototype.getLocalMatrix = function () {
  78311. this._compose();
  78312. return this._localMatrix;
  78313. };
  78314. /**
  78315. * Gets the base matrix (initial matrix which remains unchanged)
  78316. * @returns a matrix
  78317. */
  78318. Bone.prototype.getBaseMatrix = function () {
  78319. return this._baseMatrix;
  78320. };
  78321. /**
  78322. * Gets the rest pose matrix
  78323. * @returns a matrix
  78324. */
  78325. Bone.prototype.getRestPose = function () {
  78326. return this._restPose;
  78327. };
  78328. /**
  78329. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78330. */
  78331. Bone.prototype.getWorldMatrix = function () {
  78332. return this._worldTransform;
  78333. };
  78334. /**
  78335. * Sets the local matrix to rest pose matrix
  78336. */
  78337. Bone.prototype.returnToRest = function () {
  78338. this.updateMatrix(this._restPose.clone());
  78339. };
  78340. /**
  78341. * Gets the inverse of the absolute transform matrix.
  78342. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78343. * @returns a matrix
  78344. */
  78345. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78346. return this._invertedAbsoluteTransform;
  78347. };
  78348. /**
  78349. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78350. * @returns a matrix
  78351. */
  78352. Bone.prototype.getAbsoluteTransform = function () {
  78353. return this._absoluteTransform;
  78354. };
  78355. Object.defineProperty(Bone.prototype, "position", {
  78356. // Properties (matches AbstractMesh properties)
  78357. /** Gets or sets current position (in local space) */
  78358. get: function () {
  78359. this._decompose();
  78360. return this._localPosition;
  78361. },
  78362. set: function (newPosition) {
  78363. this._decompose();
  78364. this._localPosition.copyFrom(newPosition);
  78365. this._markAsDirtyAndCompose();
  78366. },
  78367. enumerable: true,
  78368. configurable: true
  78369. });
  78370. Object.defineProperty(Bone.prototype, "rotation", {
  78371. /** Gets or sets current rotation (in local space) */
  78372. get: function () {
  78373. return this.getRotation();
  78374. },
  78375. set: function (newRotation) {
  78376. this.setRotation(newRotation);
  78377. },
  78378. enumerable: true,
  78379. configurable: true
  78380. });
  78381. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78382. /** Gets or sets current rotation quaternion (in local space) */
  78383. get: function () {
  78384. this._decompose();
  78385. return this._localRotation;
  78386. },
  78387. set: function (newRotation) {
  78388. this.setRotationQuaternion(newRotation);
  78389. },
  78390. enumerable: true,
  78391. configurable: true
  78392. });
  78393. Object.defineProperty(Bone.prototype, "scaling", {
  78394. /** Gets or sets current scaling (in local space) */
  78395. get: function () {
  78396. return this.getScale();
  78397. },
  78398. set: function (newScaling) {
  78399. this.setScale(newScaling);
  78400. },
  78401. enumerable: true,
  78402. configurable: true
  78403. });
  78404. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78405. /**
  78406. * Gets the animation properties override
  78407. */
  78408. get: function () {
  78409. return this._skeleton.animationPropertiesOverride;
  78410. },
  78411. enumerable: true,
  78412. configurable: true
  78413. });
  78414. // Methods
  78415. Bone.prototype._decompose = function () {
  78416. if (!this._needToDecompose) {
  78417. return;
  78418. }
  78419. this._needToDecompose = false;
  78420. if (!this._localScaling) {
  78421. this._localScaling = BABYLON.Vector3.Zero();
  78422. this._localRotation = BABYLON.Quaternion.Zero();
  78423. this._localPosition = BABYLON.Vector3.Zero();
  78424. }
  78425. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78426. };
  78427. Bone.prototype._compose = function () {
  78428. if (!this._needToCompose) {
  78429. return;
  78430. }
  78431. this._needToCompose = false;
  78432. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78433. };
  78434. /**
  78435. * Update the base and local matrices
  78436. * @param matrix defines the new base or local matrix
  78437. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78438. * @param updateLocalMatrix defines if the local matrix should be updated
  78439. */
  78440. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78441. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78442. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78443. this._baseMatrix.copyFrom(matrix);
  78444. if (updateDifferenceMatrix) {
  78445. this._updateDifferenceMatrix();
  78446. }
  78447. if (updateLocalMatrix) {
  78448. this._localMatrix.copyFrom(matrix);
  78449. this._markAsDirtyAndDecompose();
  78450. }
  78451. else {
  78452. this.markAsDirty();
  78453. }
  78454. };
  78455. /** @hidden */
  78456. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78457. if (updateChildren === void 0) { updateChildren = true; }
  78458. if (!rootMatrix) {
  78459. rootMatrix = this._baseMatrix;
  78460. }
  78461. if (this._parent) {
  78462. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78463. }
  78464. else {
  78465. this._absoluteTransform.copyFrom(rootMatrix);
  78466. }
  78467. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78468. if (updateChildren) {
  78469. for (var index = 0; index < this.children.length; index++) {
  78470. this.children[index]._updateDifferenceMatrix();
  78471. }
  78472. }
  78473. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78474. };
  78475. /**
  78476. * Flag the bone as dirty (Forcing it to update everything)
  78477. */
  78478. Bone.prototype.markAsDirty = function () {
  78479. this._currentRenderId++;
  78480. this._childRenderId++;
  78481. this._skeleton._markAsDirty();
  78482. };
  78483. Bone.prototype._markAsDirtyAndCompose = function () {
  78484. this.markAsDirty();
  78485. this._needToCompose = true;
  78486. };
  78487. Bone.prototype._markAsDirtyAndDecompose = function () {
  78488. this.markAsDirty();
  78489. this._needToDecompose = true;
  78490. };
  78491. /**
  78492. * Copy an animation range from another bone
  78493. * @param source defines the source bone
  78494. * @param rangeName defines the range name to copy
  78495. * @param frameOffset defines the frame offset
  78496. * @param rescaleAsRequired defines if rescaling must be applied if required
  78497. * @param skelDimensionsRatio defines the scaling ratio
  78498. * @returns true if operation was successful
  78499. */
  78500. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78501. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78502. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78503. // all animation may be coming from a library skeleton, so may need to create animation
  78504. if (this.animations.length === 0) {
  78505. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78506. this.animations[0].setKeys([]);
  78507. }
  78508. // get animation info / verify there is such a range from the source bone
  78509. var sourceRange = source.animations[0].getRange(rangeName);
  78510. if (!sourceRange) {
  78511. return false;
  78512. }
  78513. var from = sourceRange.from;
  78514. var to = sourceRange.to;
  78515. var sourceKeys = source.animations[0].getKeys();
  78516. // rescaling prep
  78517. var sourceBoneLength = source.length;
  78518. var sourceParent = source.getParent();
  78519. var parent = this.getParent();
  78520. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78521. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78522. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78523. var destKeys = this.animations[0].getKeys();
  78524. // loop vars declaration
  78525. var orig;
  78526. var origTranslation;
  78527. var mat;
  78528. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78529. orig = sourceKeys[key];
  78530. if (orig.frame >= from && orig.frame <= to) {
  78531. if (rescaleAsRequired) {
  78532. mat = orig.value.clone();
  78533. // scale based on parent ratio, when bone has parent
  78534. if (parentScalingReqd) {
  78535. origTranslation = mat.getTranslation();
  78536. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78537. // scale based on skeleton dimension ratio when root bone, and value is passed
  78538. }
  78539. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78540. origTranslation = mat.getTranslation();
  78541. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78542. // use original when root bone, and no data for skelDimensionsRatio
  78543. }
  78544. else {
  78545. mat = orig.value;
  78546. }
  78547. }
  78548. else {
  78549. mat = orig.value;
  78550. }
  78551. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78552. }
  78553. }
  78554. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78555. return true;
  78556. };
  78557. /**
  78558. * Translate the bone in local or world space
  78559. * @param vec The amount to translate the bone
  78560. * @param space The space that the translation is in
  78561. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78562. */
  78563. Bone.prototype.translate = function (vec, space, mesh) {
  78564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78565. var lm = this.getLocalMatrix();
  78566. if (space == BABYLON.Space.LOCAL) {
  78567. lm.m[12] += vec.x;
  78568. lm.m[13] += vec.y;
  78569. lm.m[14] += vec.z;
  78570. }
  78571. else {
  78572. var wm = null;
  78573. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78574. if (mesh) {
  78575. wm = mesh.getWorldMatrix();
  78576. }
  78577. this._skeleton.computeAbsoluteTransforms();
  78578. var tmat = Bone._tmpMats[0];
  78579. var tvec = Bone._tmpVecs[0];
  78580. if (this._parent) {
  78581. if (mesh && wm) {
  78582. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78583. tmat.multiplyToRef(wm, tmat);
  78584. }
  78585. else {
  78586. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78587. }
  78588. }
  78589. tmat.m[12] = 0;
  78590. tmat.m[13] = 0;
  78591. tmat.m[14] = 0;
  78592. tmat.invert();
  78593. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78594. lm.m[12] += tvec.x;
  78595. lm.m[13] += tvec.y;
  78596. lm.m[14] += tvec.z;
  78597. }
  78598. this._markAsDirtyAndDecompose();
  78599. };
  78600. /**
  78601. * Set the postion of the bone in local or world space
  78602. * @param position The position to set the bone
  78603. * @param space The space that the position is in
  78604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78605. */
  78606. Bone.prototype.setPosition = function (position, space, mesh) {
  78607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78608. var lm = this.getLocalMatrix();
  78609. if (space == BABYLON.Space.LOCAL) {
  78610. lm.m[12] = position.x;
  78611. lm.m[13] = position.y;
  78612. lm.m[14] = position.z;
  78613. }
  78614. else {
  78615. var wm = null;
  78616. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78617. if (mesh) {
  78618. wm = mesh.getWorldMatrix();
  78619. }
  78620. this._skeleton.computeAbsoluteTransforms();
  78621. var tmat = Bone._tmpMats[0];
  78622. var vec = Bone._tmpVecs[0];
  78623. if (this._parent) {
  78624. if (mesh && wm) {
  78625. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78626. tmat.multiplyToRef(wm, tmat);
  78627. }
  78628. else {
  78629. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78630. }
  78631. }
  78632. tmat.invert();
  78633. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78634. lm.m[12] = vec.x;
  78635. lm.m[13] = vec.y;
  78636. lm.m[14] = vec.z;
  78637. }
  78638. this._markAsDirtyAndDecompose();
  78639. };
  78640. /**
  78641. * Set the absolute position of the bone (world space)
  78642. * @param position The position to set the bone
  78643. * @param mesh The mesh that this bone is attached to
  78644. */
  78645. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78646. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78647. };
  78648. /**
  78649. * Scale the bone on the x, y and z axes (in local space)
  78650. * @param x The amount to scale the bone on the x axis
  78651. * @param y The amount to scale the bone on the y axis
  78652. * @param z The amount to scale the bone on the z axis
  78653. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78654. */
  78655. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78656. if (scaleChildren === void 0) { scaleChildren = false; }
  78657. var locMat = this.getLocalMatrix();
  78658. // Apply new scaling on top of current local matrix
  78659. var scaleMat = Bone._tmpMats[0];
  78660. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78661. scaleMat.multiplyToRef(locMat, locMat);
  78662. // Invert scaling matrix and apply the inverse to all children
  78663. scaleMat.invert();
  78664. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78665. var child = _a[_i];
  78666. var cm = child.getLocalMatrix();
  78667. cm.multiplyToRef(scaleMat, cm);
  78668. cm.m[12] *= x;
  78669. cm.m[13] *= y;
  78670. cm.m[14] *= z;
  78671. child._markAsDirtyAndDecompose();
  78672. }
  78673. this._markAsDirtyAndDecompose();
  78674. if (scaleChildren) {
  78675. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78676. var child = _c[_b];
  78677. child.scale(x, y, z, scaleChildren);
  78678. }
  78679. }
  78680. };
  78681. /**
  78682. * Set the bone scaling in local space
  78683. * @param scale defines the scaling vector
  78684. */
  78685. Bone.prototype.setScale = function (scale) {
  78686. this._decompose();
  78687. this._localScaling.copyFrom(scale);
  78688. this._markAsDirtyAndCompose();
  78689. };
  78690. /**
  78691. * Gets the current scaling in local space
  78692. * @returns the current scaling vector
  78693. */
  78694. Bone.prototype.getScale = function () {
  78695. this._decompose();
  78696. return this._localScaling;
  78697. };
  78698. /**
  78699. * Gets the current scaling in local space and stores it in a target vector
  78700. * @param result defines the target vector
  78701. */
  78702. Bone.prototype.getScaleToRef = function (result) {
  78703. this._decompose();
  78704. result.copyFrom(this._localScaling);
  78705. };
  78706. /**
  78707. * Set the yaw, pitch, and roll of the bone in local or world space
  78708. * @param yaw The rotation of the bone on the y axis
  78709. * @param pitch The rotation of the bone on the x axis
  78710. * @param roll The rotation of the bone on the z axis
  78711. * @param space The space that the axes of rotation are in
  78712. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78713. */
  78714. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78715. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78716. if (space === BABYLON.Space.LOCAL) {
  78717. var quat = Bone._tmpQuat;
  78718. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78719. this.setRotationQuaternion(quat, space, mesh);
  78720. return;
  78721. }
  78722. var rotMatInv = Bone._tmpMats[0];
  78723. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78724. return;
  78725. }
  78726. var rotMat = Bone._tmpMats[1];
  78727. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78728. rotMatInv.multiplyToRef(rotMat, rotMat);
  78729. this._rotateWithMatrix(rotMat, space, mesh);
  78730. };
  78731. /**
  78732. * Add a rotation to the bone on an axis in local or world space
  78733. * @param axis The axis to rotate the bone on
  78734. * @param amount The amount to rotate the bone
  78735. * @param space The space that the axis is in
  78736. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78737. */
  78738. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78740. var rmat = Bone._tmpMats[0];
  78741. rmat.m[12] = 0;
  78742. rmat.m[13] = 0;
  78743. rmat.m[14] = 0;
  78744. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78745. this._rotateWithMatrix(rmat, space, mesh);
  78746. };
  78747. /**
  78748. * Set the rotation of the bone to a particular axis angle in local or world space
  78749. * @param axis The axis to rotate the bone on
  78750. * @param angle The angle that the bone should be rotated to
  78751. * @param space The space that the axis is in
  78752. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78753. */
  78754. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78756. if (space === BABYLON.Space.LOCAL) {
  78757. var quat = Bone._tmpQuat;
  78758. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78759. this.setRotationQuaternion(quat, space, mesh);
  78760. return;
  78761. }
  78762. var rotMatInv = Bone._tmpMats[0];
  78763. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78764. return;
  78765. }
  78766. var rotMat = Bone._tmpMats[1];
  78767. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78768. rotMatInv.multiplyToRef(rotMat, rotMat);
  78769. this._rotateWithMatrix(rotMat, space, mesh);
  78770. };
  78771. /**
  78772. * Set the euler rotation of the bone in local of world space
  78773. * @param rotation The euler rotation that the bone should be set to
  78774. * @param space The space that the rotation is in
  78775. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78776. */
  78777. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78778. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78779. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78780. };
  78781. /**
  78782. * Set the quaternion rotation of the bone in local of world space
  78783. * @param quat The quaternion rotation that the bone should be set to
  78784. * @param space The space that the rotation is in
  78785. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78786. */
  78787. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78789. if (space === BABYLON.Space.LOCAL) {
  78790. this._decompose();
  78791. this._localRotation.copyFrom(quat);
  78792. this._markAsDirtyAndCompose();
  78793. return;
  78794. }
  78795. var rotMatInv = Bone._tmpMats[0];
  78796. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78797. return;
  78798. }
  78799. var rotMat = Bone._tmpMats[1];
  78800. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78801. rotMatInv.multiplyToRef(rotMat, rotMat);
  78802. this._rotateWithMatrix(rotMat, space, mesh);
  78803. };
  78804. /**
  78805. * Set the rotation matrix of the bone in local of world space
  78806. * @param rotMat The rotation matrix that the bone should be set to
  78807. * @param space The space that the rotation is in
  78808. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78809. */
  78810. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78811. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78812. if (space === BABYLON.Space.LOCAL) {
  78813. var quat = Bone._tmpQuat;
  78814. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78815. this.setRotationQuaternion(quat, space, mesh);
  78816. return;
  78817. }
  78818. var rotMatInv = Bone._tmpMats[0];
  78819. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78820. return;
  78821. }
  78822. var rotMat2 = Bone._tmpMats[1];
  78823. rotMat2.copyFrom(rotMat);
  78824. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78825. this._rotateWithMatrix(rotMat2, space, mesh);
  78826. };
  78827. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78828. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78829. var lmat = this.getLocalMatrix();
  78830. var lx = lmat.m[12];
  78831. var ly = lmat.m[13];
  78832. var lz = lmat.m[14];
  78833. var parent = this.getParent();
  78834. var parentScale = Bone._tmpMats[3];
  78835. var parentScaleInv = Bone._tmpMats[4];
  78836. if (parent && space == BABYLON.Space.WORLD) {
  78837. if (mesh) {
  78838. parentScale.copyFrom(mesh.getWorldMatrix());
  78839. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78840. }
  78841. else {
  78842. parentScale.copyFrom(parent.getAbsoluteTransform());
  78843. }
  78844. parentScaleInv.copyFrom(parentScale);
  78845. parentScaleInv.invert();
  78846. lmat.multiplyToRef(parentScale, lmat);
  78847. lmat.multiplyToRef(rmat, lmat);
  78848. lmat.multiplyToRef(parentScaleInv, lmat);
  78849. }
  78850. else {
  78851. if (space == BABYLON.Space.WORLD && mesh) {
  78852. parentScale.copyFrom(mesh.getWorldMatrix());
  78853. parentScaleInv.copyFrom(parentScale);
  78854. parentScaleInv.invert();
  78855. lmat.multiplyToRef(parentScale, lmat);
  78856. lmat.multiplyToRef(rmat, lmat);
  78857. lmat.multiplyToRef(parentScaleInv, lmat);
  78858. }
  78859. else {
  78860. lmat.multiplyToRef(rmat, lmat);
  78861. }
  78862. }
  78863. lmat.m[12] = lx;
  78864. lmat.m[13] = ly;
  78865. lmat.m[14] = lz;
  78866. this.computeAbsoluteTransforms();
  78867. this._markAsDirtyAndDecompose();
  78868. };
  78869. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78870. var scaleMatrix = Bone._tmpMats[2];
  78871. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78872. if (mesh) {
  78873. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78874. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78875. }
  78876. rotMatInv.invert();
  78877. if (isNaN(rotMatInv.m[0])) {
  78878. // Matrix failed to invert.
  78879. // This can happen if scale is zero for example.
  78880. return false;
  78881. }
  78882. scaleMatrix.m[0] *= this._scalingDeterminant;
  78883. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78884. return true;
  78885. };
  78886. /**
  78887. * Get the position of the bone in local or world space
  78888. * @param space The space that the returned position is in
  78889. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78890. * @returns The position of the bone
  78891. */
  78892. Bone.prototype.getPosition = function (space, mesh) {
  78893. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78894. if (mesh === void 0) { mesh = null; }
  78895. var pos = BABYLON.Vector3.Zero();
  78896. this.getPositionToRef(space, mesh, pos);
  78897. return pos;
  78898. };
  78899. /**
  78900. * Copy the position of the bone to a vector3 in local or world space
  78901. * @param space The space that the returned position is in
  78902. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78903. * @param result The vector3 to copy the position to
  78904. */
  78905. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78907. if (space == BABYLON.Space.LOCAL) {
  78908. var lm = this.getLocalMatrix();
  78909. result.x = lm.m[12];
  78910. result.y = lm.m[13];
  78911. result.z = lm.m[14];
  78912. }
  78913. else {
  78914. var wm = null;
  78915. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78916. if (mesh) {
  78917. wm = mesh.getWorldMatrix();
  78918. }
  78919. this._skeleton.computeAbsoluteTransforms();
  78920. var tmat = Bone._tmpMats[0];
  78921. if (mesh && wm) {
  78922. tmat.copyFrom(this.getAbsoluteTransform());
  78923. tmat.multiplyToRef(wm, tmat);
  78924. }
  78925. else {
  78926. tmat = this.getAbsoluteTransform();
  78927. }
  78928. result.x = tmat.m[12];
  78929. result.y = tmat.m[13];
  78930. result.z = tmat.m[14];
  78931. }
  78932. };
  78933. /**
  78934. * Get the absolute position of the bone (world space)
  78935. * @param mesh The mesh that this bone is attached to
  78936. * @returns The absolute position of the bone
  78937. */
  78938. Bone.prototype.getAbsolutePosition = function (mesh) {
  78939. if (mesh === void 0) { mesh = null; }
  78940. var pos = BABYLON.Vector3.Zero();
  78941. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78942. return pos;
  78943. };
  78944. /**
  78945. * Copy the absolute position of the bone (world space) to the result param
  78946. * @param mesh The mesh that this bone is attached to
  78947. * @param result The vector3 to copy the absolute position to
  78948. */
  78949. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78950. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78951. };
  78952. /**
  78953. * Compute the absolute transforms of this bone and its children
  78954. */
  78955. Bone.prototype.computeAbsoluteTransforms = function () {
  78956. this._compose();
  78957. if (this._parent) {
  78958. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78959. }
  78960. else {
  78961. this._absoluteTransform.copyFrom(this._localMatrix);
  78962. var poseMatrix = this._skeleton.getPoseMatrix();
  78963. if (poseMatrix) {
  78964. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78965. }
  78966. }
  78967. var children = this.children;
  78968. var len = children.length;
  78969. for (var i = 0; i < len; i++) {
  78970. children[i].computeAbsoluteTransforms();
  78971. }
  78972. };
  78973. /**
  78974. * Get the world direction from an axis that is in the local space of the bone
  78975. * @param localAxis The local direction that is used to compute the world direction
  78976. * @param mesh The mesh that this bone is attached to
  78977. * @returns The world direction
  78978. */
  78979. Bone.prototype.getDirection = function (localAxis, mesh) {
  78980. if (mesh === void 0) { mesh = null; }
  78981. var result = BABYLON.Vector3.Zero();
  78982. this.getDirectionToRef(localAxis, mesh, result);
  78983. return result;
  78984. };
  78985. /**
  78986. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78987. * @param localAxis The local direction that is used to compute the world direction
  78988. * @param mesh The mesh that this bone is attached to
  78989. * @param result The vector3 that the world direction will be copied to
  78990. */
  78991. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78992. if (mesh === void 0) { mesh = null; }
  78993. var wm = null;
  78994. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78995. if (mesh) {
  78996. wm = mesh.getWorldMatrix();
  78997. }
  78998. this._skeleton.computeAbsoluteTransforms();
  78999. var mat = Bone._tmpMats[0];
  79000. mat.copyFrom(this.getAbsoluteTransform());
  79001. if (mesh && wm) {
  79002. mat.multiplyToRef(wm, mat);
  79003. }
  79004. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79005. result.normalize();
  79006. };
  79007. /**
  79008. * Get the euler rotation of the bone in local or world space
  79009. * @param space The space that the rotation should be in
  79010. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79011. * @returns The euler rotation
  79012. */
  79013. Bone.prototype.getRotation = function (space, mesh) {
  79014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79015. if (mesh === void 0) { mesh = null; }
  79016. var result = BABYLON.Vector3.Zero();
  79017. this.getRotationToRef(space, mesh, result);
  79018. return result;
  79019. };
  79020. /**
  79021. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79022. * @param space The space that the rotation should be in
  79023. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79024. * @param result The vector3 that the rotation should be copied to
  79025. */
  79026. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79028. if (mesh === void 0) { mesh = null; }
  79029. var quat = Bone._tmpQuat;
  79030. this.getRotationQuaternionToRef(space, mesh, quat);
  79031. quat.toEulerAnglesToRef(result);
  79032. };
  79033. /**
  79034. * Get the quaternion rotation of the bone in either local or world space
  79035. * @param space The space that the rotation should be in
  79036. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79037. * @returns The quaternion rotation
  79038. */
  79039. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79041. if (mesh === void 0) { mesh = null; }
  79042. var result = BABYLON.Quaternion.Identity();
  79043. this.getRotationQuaternionToRef(space, mesh, result);
  79044. return result;
  79045. };
  79046. /**
  79047. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79048. * @param space The space that the rotation should be in
  79049. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79050. * @param result The quaternion that the rotation should be copied to
  79051. */
  79052. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79054. if (mesh === void 0) { mesh = null; }
  79055. if (space == BABYLON.Space.LOCAL) {
  79056. this._decompose();
  79057. result.copyFrom(this._localRotation);
  79058. }
  79059. else {
  79060. var mat = Bone._tmpMats[0];
  79061. var amat = this.getAbsoluteTransform();
  79062. if (mesh) {
  79063. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79064. }
  79065. else {
  79066. mat.copyFrom(amat);
  79067. }
  79068. mat.m[0] *= this._scalingDeterminant;
  79069. mat.m[1] *= this._scalingDeterminant;
  79070. mat.m[2] *= this._scalingDeterminant;
  79071. mat.decompose(undefined, result, undefined);
  79072. }
  79073. };
  79074. /**
  79075. * Get the rotation matrix of the bone in local or world space
  79076. * @param space The space that the rotation should be in
  79077. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79078. * @returns The rotation matrix
  79079. */
  79080. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79082. var result = BABYLON.Matrix.Identity();
  79083. this.getRotationMatrixToRef(space, mesh, result);
  79084. return result;
  79085. };
  79086. /**
  79087. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79088. * @param space The space that the rotation should be in
  79089. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79090. * @param result The quaternion that the rotation should be copied to
  79091. */
  79092. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79094. if (space == BABYLON.Space.LOCAL) {
  79095. this.getLocalMatrix().getRotationMatrixToRef(result);
  79096. }
  79097. else {
  79098. var mat = Bone._tmpMats[0];
  79099. var amat = this.getAbsoluteTransform();
  79100. if (mesh) {
  79101. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79102. }
  79103. else {
  79104. mat.copyFrom(amat);
  79105. }
  79106. mat.m[0] *= this._scalingDeterminant;
  79107. mat.m[1] *= this._scalingDeterminant;
  79108. mat.m[2] *= this._scalingDeterminant;
  79109. mat.getRotationMatrixToRef(result);
  79110. }
  79111. };
  79112. /**
  79113. * Get the world position of a point that is in the local space of the bone
  79114. * @param position The local position
  79115. * @param mesh The mesh that this bone is attached to
  79116. * @returns The world position
  79117. */
  79118. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79119. if (mesh === void 0) { mesh = null; }
  79120. var result = BABYLON.Vector3.Zero();
  79121. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79122. return result;
  79123. };
  79124. /**
  79125. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79126. * @param position The local position
  79127. * @param mesh The mesh that this bone is attached to
  79128. * @param result The vector3 that the world position should be copied to
  79129. */
  79130. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79131. if (mesh === void 0) { mesh = null; }
  79132. var wm = null;
  79133. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79134. if (mesh) {
  79135. wm = mesh.getWorldMatrix();
  79136. }
  79137. this._skeleton.computeAbsoluteTransforms();
  79138. var tmat = Bone._tmpMats[0];
  79139. if (mesh && wm) {
  79140. tmat.copyFrom(this.getAbsoluteTransform());
  79141. tmat.multiplyToRef(wm, tmat);
  79142. }
  79143. else {
  79144. tmat = this.getAbsoluteTransform();
  79145. }
  79146. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79147. };
  79148. /**
  79149. * Get the local position of a point that is in world space
  79150. * @param position The world position
  79151. * @param mesh The mesh that this bone is attached to
  79152. * @returns The local position
  79153. */
  79154. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79155. if (mesh === void 0) { mesh = null; }
  79156. var result = BABYLON.Vector3.Zero();
  79157. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79158. return result;
  79159. };
  79160. /**
  79161. * Get the local position of a point that is in world space and copy it to the result param
  79162. * @param position The world position
  79163. * @param mesh The mesh that this bone is attached to
  79164. * @param result The vector3 that the local position should be copied to
  79165. */
  79166. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79167. if (mesh === void 0) { mesh = null; }
  79168. var wm = null;
  79169. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79170. if (mesh) {
  79171. wm = mesh.getWorldMatrix();
  79172. }
  79173. this._skeleton.computeAbsoluteTransforms();
  79174. var tmat = Bone._tmpMats[0];
  79175. tmat.copyFrom(this.getAbsoluteTransform());
  79176. if (mesh && wm) {
  79177. tmat.multiplyToRef(wm, tmat);
  79178. }
  79179. tmat.invert();
  79180. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79181. };
  79182. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79183. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79184. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79185. return Bone;
  79186. }(BABYLON.Node));
  79187. BABYLON.Bone = Bone;
  79188. })(BABYLON || (BABYLON = {}));
  79189. //# sourceMappingURL=babylon.bone.js.map
  79190. var BABYLON;
  79191. (function (BABYLON) {
  79192. /**
  79193. * Class used to apply inverse kinematics to bones
  79194. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79195. */
  79196. var BoneIKController = /** @class */ (function () {
  79197. /**
  79198. * Creates a new BoneIKController
  79199. * @param mesh defines the mesh to control
  79200. * @param bone defines the bone to control
  79201. * @param options defines options to set up the controller
  79202. */
  79203. function BoneIKController(mesh, bone, options) {
  79204. /**
  79205. * Gets or sets the target position
  79206. */
  79207. this.targetPosition = BABYLON.Vector3.Zero();
  79208. /**
  79209. * Gets or sets the pole target position
  79210. */
  79211. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79212. /**
  79213. * Gets or sets the pole target local offset
  79214. */
  79215. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79216. /**
  79217. * Gets or sets the pole angle
  79218. */
  79219. this.poleAngle = 0;
  79220. /**
  79221. * 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)
  79222. */
  79223. this.slerpAmount = 1;
  79224. this._bone1Quat = BABYLON.Quaternion.Identity();
  79225. this._bone1Mat = BABYLON.Matrix.Identity();
  79226. this._bone2Ang = Math.PI;
  79227. this._maxAngle = Math.PI;
  79228. this._rightHandedSystem = false;
  79229. this._bendAxis = BABYLON.Vector3.Right();
  79230. this._slerping = false;
  79231. this._adjustRoll = 0;
  79232. this._bone2 = bone;
  79233. this._bone1 = bone.getParent();
  79234. if (!this._bone1) {
  79235. return;
  79236. }
  79237. this.mesh = mesh;
  79238. var bonePos = bone.getPosition();
  79239. if (bone.getAbsoluteTransform().determinant() > 0) {
  79240. this._rightHandedSystem = true;
  79241. this._bendAxis.x = 0;
  79242. this._bendAxis.y = 0;
  79243. this._bendAxis.z = -1;
  79244. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79245. this._adjustRoll = Math.PI * .5;
  79246. this._bendAxis.z = 1;
  79247. }
  79248. }
  79249. if (this._bone1.length) {
  79250. var boneScale1 = this._bone1.getScale();
  79251. var boneScale2 = this._bone2.getScale();
  79252. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79253. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79254. }
  79255. else if (this._bone1.children[0]) {
  79256. mesh.computeWorldMatrix(true);
  79257. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79258. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79259. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79260. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79261. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79262. }
  79263. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79264. this.maxAngle = Math.PI;
  79265. if (options) {
  79266. if (options.targetMesh) {
  79267. this.targetMesh = options.targetMesh;
  79268. this.targetMesh.computeWorldMatrix(true);
  79269. }
  79270. if (options.poleTargetMesh) {
  79271. this.poleTargetMesh = options.poleTargetMesh;
  79272. this.poleTargetMesh.computeWorldMatrix(true);
  79273. }
  79274. else if (options.poleTargetBone) {
  79275. this.poleTargetBone = options.poleTargetBone;
  79276. }
  79277. else if (this._bone1.getParent()) {
  79278. this.poleTargetBone = this._bone1.getParent();
  79279. }
  79280. if (options.poleTargetLocalOffset) {
  79281. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79282. }
  79283. if (options.poleAngle) {
  79284. this.poleAngle = options.poleAngle;
  79285. }
  79286. if (options.bendAxis) {
  79287. this._bendAxis.copyFrom(options.bendAxis);
  79288. }
  79289. if (options.maxAngle) {
  79290. this.maxAngle = options.maxAngle;
  79291. }
  79292. if (options.slerpAmount) {
  79293. this.slerpAmount = options.slerpAmount;
  79294. }
  79295. }
  79296. }
  79297. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79298. /**
  79299. * Gets or sets maximum allowed angle
  79300. */
  79301. get: function () {
  79302. return this._maxAngle;
  79303. },
  79304. set: function (value) {
  79305. this._setMaxAngle(value);
  79306. },
  79307. enumerable: true,
  79308. configurable: true
  79309. });
  79310. BoneIKController.prototype._setMaxAngle = function (ang) {
  79311. if (ang < 0) {
  79312. ang = 0;
  79313. }
  79314. if (ang > Math.PI || ang == undefined) {
  79315. ang = Math.PI;
  79316. }
  79317. this._maxAngle = ang;
  79318. var a = this._bone1Length;
  79319. var b = this._bone2Length;
  79320. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79321. };
  79322. /**
  79323. * Force the controller to update the bones
  79324. */
  79325. BoneIKController.prototype.update = function () {
  79326. var bone1 = this._bone1;
  79327. if (!bone1) {
  79328. return;
  79329. }
  79330. var target = this.targetPosition;
  79331. var poleTarget = this.poleTargetPosition;
  79332. var mat1 = BoneIKController._tmpMats[0];
  79333. var mat2 = BoneIKController._tmpMats[1];
  79334. if (this.targetMesh) {
  79335. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79336. }
  79337. if (this.poleTargetBone) {
  79338. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79339. }
  79340. else if (this.poleTargetMesh) {
  79341. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79342. }
  79343. var bonePos = BoneIKController._tmpVecs[0];
  79344. var zaxis = BoneIKController._tmpVecs[1];
  79345. var xaxis = BoneIKController._tmpVecs[2];
  79346. var yaxis = BoneIKController._tmpVecs[3];
  79347. var upAxis = BoneIKController._tmpVecs[4];
  79348. var _tmpQuat = BoneIKController._tmpQuat;
  79349. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79350. poleTarget.subtractToRef(bonePos, upAxis);
  79351. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79352. upAxis.y = 1;
  79353. }
  79354. else {
  79355. upAxis.normalize();
  79356. }
  79357. target.subtractToRef(bonePos, yaxis);
  79358. yaxis.normalize();
  79359. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79360. zaxis.normalize();
  79361. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79362. xaxis.normalize();
  79363. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79364. var a = this._bone1Length;
  79365. var b = this._bone2Length;
  79366. var c = BABYLON.Vector3.Distance(bonePos, target);
  79367. if (this._maxReach > 0) {
  79368. c = Math.min(this._maxReach, c);
  79369. }
  79370. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79371. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79372. if (acosa > 1) {
  79373. acosa = 1;
  79374. }
  79375. if (acosb > 1) {
  79376. acosb = 1;
  79377. }
  79378. if (acosa < -1) {
  79379. acosa = -1;
  79380. }
  79381. if (acosb < -1) {
  79382. acosb = -1;
  79383. }
  79384. var angA = Math.acos(acosa);
  79385. var angB = Math.acos(acosb);
  79386. var angC = -angA - angB;
  79387. if (this._rightHandedSystem) {
  79388. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79389. mat2.multiplyToRef(mat1, mat1);
  79390. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79391. mat2.multiplyToRef(mat1, mat1);
  79392. }
  79393. else {
  79394. var _tmpVec = BoneIKController._tmpVecs[5];
  79395. _tmpVec.copyFrom(this._bendAxis);
  79396. _tmpVec.x *= -1;
  79397. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79398. mat2.multiplyToRef(mat1, mat1);
  79399. }
  79400. if (this.poleAngle) {
  79401. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79402. mat1.multiplyToRef(mat2, mat1);
  79403. }
  79404. if (this._bone1) {
  79405. if (this.slerpAmount < 1) {
  79406. if (!this._slerping) {
  79407. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79408. }
  79409. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79410. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79411. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79412. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79413. this._slerping = true;
  79414. }
  79415. else {
  79416. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79417. this._bone1Mat.copyFrom(mat1);
  79418. this._slerping = false;
  79419. }
  79420. }
  79421. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79422. this._bone2Ang = angC;
  79423. };
  79424. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79425. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79426. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79427. return BoneIKController;
  79428. }());
  79429. BABYLON.BoneIKController = BoneIKController;
  79430. })(BABYLON || (BABYLON = {}));
  79431. //# sourceMappingURL=babylon.boneIKController.js.map
  79432. var BABYLON;
  79433. (function (BABYLON) {
  79434. /**
  79435. * Class used to make a bone look toward a point in space
  79436. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79437. */
  79438. var BoneLookController = /** @class */ (function () {
  79439. /**
  79440. * Create a BoneLookController
  79441. * @param mesh the mesh that the bone belongs to
  79442. * @param bone the bone that will be looking to the target
  79443. * @param target the target Vector3 to look at
  79444. * @param settings optional settings:
  79445. * * maxYaw: the maximum angle the bone will yaw to
  79446. * * minYaw: the minimum angle the bone will yaw to
  79447. * * maxPitch: the maximum angle the bone will pitch to
  79448. * * minPitch: the minimum angle the bone will yaw to
  79449. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79450. * * upAxis: the up axis of the coordinate system
  79451. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79452. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79453. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79454. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79455. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79456. * * adjustRoll: used to make an adjustment to the roll of the bone
  79457. **/
  79458. function BoneLookController(mesh, bone, target, options) {
  79459. /**
  79460. * The up axis of the coordinate system that is used when the bone is rotated
  79461. */
  79462. this.upAxis = BABYLON.Vector3.Up();
  79463. /**
  79464. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79465. */
  79466. this.upAxisSpace = BABYLON.Space.LOCAL;
  79467. /**
  79468. * Used to make an adjustment to the yaw of the bone
  79469. */
  79470. this.adjustYaw = 0;
  79471. /**
  79472. * Used to make an adjustment to the pitch of the bone
  79473. */
  79474. this.adjustPitch = 0;
  79475. /**
  79476. * Used to make an adjustment to the roll of the bone
  79477. */
  79478. this.adjustRoll = 0;
  79479. /**
  79480. * 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)
  79481. */
  79482. this.slerpAmount = 1;
  79483. this._boneQuat = BABYLON.Quaternion.Identity();
  79484. this._slerping = false;
  79485. this._firstFrameSkipped = false;
  79486. this._fowardAxis = BABYLON.Vector3.Forward();
  79487. this.mesh = mesh;
  79488. this.bone = bone;
  79489. this.target = target;
  79490. if (options) {
  79491. if (options.adjustYaw) {
  79492. this.adjustYaw = options.adjustYaw;
  79493. }
  79494. if (options.adjustPitch) {
  79495. this.adjustPitch = options.adjustPitch;
  79496. }
  79497. if (options.adjustRoll) {
  79498. this.adjustRoll = options.adjustRoll;
  79499. }
  79500. if (options.maxYaw != null) {
  79501. this.maxYaw = options.maxYaw;
  79502. }
  79503. else {
  79504. this.maxYaw = Math.PI;
  79505. }
  79506. if (options.minYaw != null) {
  79507. this.minYaw = options.minYaw;
  79508. }
  79509. else {
  79510. this.minYaw = -Math.PI;
  79511. }
  79512. if (options.maxPitch != null) {
  79513. this.maxPitch = options.maxPitch;
  79514. }
  79515. else {
  79516. this.maxPitch = Math.PI;
  79517. }
  79518. if (options.minPitch != null) {
  79519. this.minPitch = options.minPitch;
  79520. }
  79521. else {
  79522. this.minPitch = -Math.PI;
  79523. }
  79524. if (options.slerpAmount != null) {
  79525. this.slerpAmount = options.slerpAmount;
  79526. }
  79527. if (options.upAxis != null) {
  79528. this.upAxis = options.upAxis;
  79529. }
  79530. if (options.upAxisSpace != null) {
  79531. this.upAxisSpace = options.upAxisSpace;
  79532. }
  79533. if (options.yawAxis != null || options.pitchAxis != null) {
  79534. var newYawAxis = BABYLON.Axis.Y;
  79535. var newPitchAxis = BABYLON.Axis.X;
  79536. if (options.yawAxis != null) {
  79537. newYawAxis = options.yawAxis.clone();
  79538. newYawAxis.normalize();
  79539. }
  79540. if (options.pitchAxis != null) {
  79541. newPitchAxis = options.pitchAxis.clone();
  79542. newPitchAxis.normalize();
  79543. }
  79544. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79545. this._transformYawPitch = BABYLON.Matrix.Identity();
  79546. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79547. this._transformYawPitchInv = this._transformYawPitch.clone();
  79548. this._transformYawPitch.invert();
  79549. }
  79550. }
  79551. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79552. this.upAxisSpace = BABYLON.Space.LOCAL;
  79553. }
  79554. }
  79555. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79556. /**
  79557. * Gets or sets the minimum yaw angle that the bone can look to
  79558. */
  79559. get: function () {
  79560. return this._minYaw;
  79561. },
  79562. set: function (value) {
  79563. this._minYaw = value;
  79564. this._minYawSin = Math.sin(value);
  79565. this._minYawCos = Math.cos(value);
  79566. if (this._maxYaw != null) {
  79567. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79568. this._yawRange = this._maxYaw - this._minYaw;
  79569. }
  79570. },
  79571. enumerable: true,
  79572. configurable: true
  79573. });
  79574. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79575. /**
  79576. * Gets or sets the maximum yaw angle that the bone can look to
  79577. */
  79578. get: function () {
  79579. return this._maxYaw;
  79580. },
  79581. set: function (value) {
  79582. this._maxYaw = value;
  79583. this._maxYawSin = Math.sin(value);
  79584. this._maxYawCos = Math.cos(value);
  79585. if (this._minYaw != null) {
  79586. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79587. this._yawRange = this._maxYaw - this._minYaw;
  79588. }
  79589. },
  79590. enumerable: true,
  79591. configurable: true
  79592. });
  79593. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79594. /**
  79595. * Gets or sets the minimum pitch angle that the bone can look to
  79596. */
  79597. get: function () {
  79598. return this._minPitch;
  79599. },
  79600. set: function (value) {
  79601. this._minPitch = value;
  79602. this._minPitchTan = Math.tan(value);
  79603. },
  79604. enumerable: true,
  79605. configurable: true
  79606. });
  79607. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79608. /**
  79609. * Gets or sets the maximum pitch angle that the bone can look to
  79610. */
  79611. get: function () {
  79612. return this._maxPitch;
  79613. },
  79614. set: function (value) {
  79615. this._maxPitch = value;
  79616. this._maxPitchTan = Math.tan(value);
  79617. },
  79618. enumerable: true,
  79619. configurable: true
  79620. });
  79621. /**
  79622. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79623. */
  79624. BoneLookController.prototype.update = function () {
  79625. //skip the first frame when slerping so that the mesh rotation is correct
  79626. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79627. this._firstFrameSkipped = true;
  79628. return;
  79629. }
  79630. var bone = this.bone;
  79631. var bonePos = BoneLookController._tmpVecs[0];
  79632. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79633. var target = this.target;
  79634. var _tmpMat1 = BoneLookController._tmpMats[0];
  79635. var _tmpMat2 = BoneLookController._tmpMats[1];
  79636. var mesh = this.mesh;
  79637. var parentBone = bone.getParent();
  79638. var upAxis = BoneLookController._tmpVecs[1];
  79639. upAxis.copyFrom(this.upAxis);
  79640. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79641. if (this._transformYawPitch) {
  79642. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79643. }
  79644. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79645. }
  79646. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79647. mesh.getDirectionToRef(upAxis, upAxis);
  79648. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79649. upAxis.normalize();
  79650. }
  79651. }
  79652. var checkYaw = false;
  79653. var checkPitch = false;
  79654. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79655. checkYaw = true;
  79656. }
  79657. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79658. checkPitch = true;
  79659. }
  79660. if (checkYaw || checkPitch) {
  79661. var spaceMat = BoneLookController._tmpMats[2];
  79662. var spaceMatInv = BoneLookController._tmpMats[3];
  79663. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79664. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79665. }
  79666. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79667. spaceMat.copyFrom(mesh.getWorldMatrix());
  79668. }
  79669. else {
  79670. var forwardAxis = BoneLookController._tmpVecs[2];
  79671. forwardAxis.copyFrom(this._fowardAxis);
  79672. if (this._transformYawPitch) {
  79673. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79674. }
  79675. if (parentBone) {
  79676. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79677. }
  79678. else {
  79679. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79680. }
  79681. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79682. rightAxis.normalize();
  79683. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79684. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79685. }
  79686. spaceMat.invertToRef(spaceMatInv);
  79687. var xzlen = null;
  79688. if (checkPitch) {
  79689. var localTarget = BoneLookController._tmpVecs[3];
  79690. target.subtractToRef(bonePos, localTarget);
  79691. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79692. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79693. var pitch = Math.atan2(localTarget.y, xzlen);
  79694. var newPitch = pitch;
  79695. if (pitch > this._maxPitch) {
  79696. localTarget.y = this._maxPitchTan * xzlen;
  79697. newPitch = this._maxPitch;
  79698. }
  79699. else if (pitch < this._minPitch) {
  79700. localTarget.y = this._minPitchTan * xzlen;
  79701. newPitch = this._minPitch;
  79702. }
  79703. if (pitch != newPitch) {
  79704. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79705. localTarget.addInPlace(bonePos);
  79706. target = localTarget;
  79707. }
  79708. }
  79709. if (checkYaw) {
  79710. var localTarget = BoneLookController._tmpVecs[4];
  79711. target.subtractToRef(bonePos, localTarget);
  79712. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79713. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79714. var newYaw = yaw;
  79715. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79716. if (xzlen == null) {
  79717. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79718. }
  79719. if (this._yawRange > Math.PI) {
  79720. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79721. localTarget.z = this._maxYawCos * xzlen;
  79722. localTarget.x = this._maxYawSin * xzlen;
  79723. newYaw = this._maxYaw;
  79724. }
  79725. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79726. localTarget.z = this._minYawCos * xzlen;
  79727. localTarget.x = this._minYawSin * xzlen;
  79728. newYaw = this._minYaw;
  79729. }
  79730. }
  79731. else {
  79732. if (yaw > this._maxYaw) {
  79733. localTarget.z = this._maxYawCos * xzlen;
  79734. localTarget.x = this._maxYawSin * xzlen;
  79735. newYaw = this._maxYaw;
  79736. }
  79737. else if (yaw < this._minYaw) {
  79738. localTarget.z = this._minYawCos * xzlen;
  79739. localTarget.x = this._minYawSin * xzlen;
  79740. newYaw = this._minYaw;
  79741. }
  79742. }
  79743. }
  79744. if (this._slerping && this._yawRange > Math.PI) {
  79745. //are we going to be crossing into the min/max region?
  79746. var boneFwd = BoneLookController._tmpVecs[8];
  79747. boneFwd.copyFrom(BABYLON.Axis.Z);
  79748. if (this._transformYawPitch) {
  79749. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79750. }
  79751. var boneRotMat = BoneLookController._tmpMats[4];
  79752. this._boneQuat.toRotationMatrix(boneRotMat);
  79753. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79754. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79755. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79756. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79757. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79758. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79759. if (angBtwTar > angBtwMidYaw) {
  79760. if (xzlen == null) {
  79761. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79762. }
  79763. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79764. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79765. if (angBtwMin < angBtwMax) {
  79766. newYaw = boneYaw + Math.PI * .75;
  79767. localTarget.z = Math.cos(newYaw) * xzlen;
  79768. localTarget.x = Math.sin(newYaw) * xzlen;
  79769. }
  79770. else {
  79771. newYaw = boneYaw - Math.PI * .75;
  79772. localTarget.z = Math.cos(newYaw) * xzlen;
  79773. localTarget.x = Math.sin(newYaw) * xzlen;
  79774. }
  79775. }
  79776. }
  79777. if (yaw != newYaw) {
  79778. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79779. localTarget.addInPlace(bonePos);
  79780. target = localTarget;
  79781. }
  79782. }
  79783. }
  79784. var zaxis = BoneLookController._tmpVecs[5];
  79785. var xaxis = BoneLookController._tmpVecs[6];
  79786. var yaxis = BoneLookController._tmpVecs[7];
  79787. var _tmpQuat = BoneLookController._tmpQuat;
  79788. target.subtractToRef(bonePos, zaxis);
  79789. zaxis.normalize();
  79790. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79791. xaxis.normalize();
  79792. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79793. yaxis.normalize();
  79794. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79795. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79796. return;
  79797. }
  79798. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79799. return;
  79800. }
  79801. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79802. return;
  79803. }
  79804. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79805. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79806. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79807. }
  79808. if (this.slerpAmount < 1) {
  79809. if (!this._slerping) {
  79810. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79811. }
  79812. if (this._transformYawPitch) {
  79813. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79814. }
  79815. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79816. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79817. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79818. this._slerping = true;
  79819. }
  79820. else {
  79821. if (this._transformYawPitch) {
  79822. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79823. }
  79824. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79825. this._slerping = false;
  79826. }
  79827. };
  79828. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79829. var angDiff = ang2 - ang1;
  79830. angDiff %= Math.PI * 2;
  79831. if (angDiff > Math.PI) {
  79832. angDiff -= Math.PI * 2;
  79833. }
  79834. else if (angDiff < -Math.PI) {
  79835. angDiff += Math.PI * 2;
  79836. }
  79837. return angDiff;
  79838. };
  79839. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79840. ang1 %= (2 * Math.PI);
  79841. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79842. ang2 %= (2 * Math.PI);
  79843. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79844. var ab = 0;
  79845. if (ang1 < ang2) {
  79846. ab = ang2 - ang1;
  79847. }
  79848. else {
  79849. ab = ang1 - ang2;
  79850. }
  79851. if (ab > Math.PI) {
  79852. ab = Math.PI * 2 - ab;
  79853. }
  79854. return ab;
  79855. };
  79856. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79857. ang %= (2 * Math.PI);
  79858. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79859. ang1 %= (2 * Math.PI);
  79860. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79861. ang2 %= (2 * Math.PI);
  79862. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79863. if (ang1 < ang2) {
  79864. if (ang > ang1 && ang < ang2) {
  79865. return true;
  79866. }
  79867. }
  79868. else {
  79869. if (ang > ang2 && ang < ang1) {
  79870. return true;
  79871. }
  79872. }
  79873. return false;
  79874. };
  79875. 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()];
  79876. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79877. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79878. return BoneLookController;
  79879. }());
  79880. BABYLON.BoneLookController = BoneLookController;
  79881. })(BABYLON || (BABYLON = {}));
  79882. //# sourceMappingURL=babylon.boneLookController.js.map
  79883. var BABYLON;
  79884. (function (BABYLON) {
  79885. /**
  79886. * Class used to handle skinning animations
  79887. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79888. */
  79889. var Skeleton = /** @class */ (function () {
  79890. /**
  79891. * Creates a new skeleton
  79892. * @param name defines the skeleton name
  79893. * @param id defines the skeleton Id
  79894. * @param scene defines the hosting scene
  79895. */
  79896. function Skeleton(
  79897. /** defines the skeleton name */
  79898. name,
  79899. /** defines the skeleton Id */
  79900. id, scene) {
  79901. this.name = name;
  79902. this.id = id;
  79903. /**
  79904. * Gets the list of child bones
  79905. */
  79906. this.bones = new Array();
  79907. /**
  79908. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79909. */
  79910. this.needInitialSkinMatrix = false;
  79911. this._isDirty = true;
  79912. this._meshesWithPoseMatrix = new Array();
  79913. this._identity = BABYLON.Matrix.Identity();
  79914. this._ranges = {};
  79915. this._lastAbsoluteTransformsUpdateId = -1;
  79916. /**
  79917. * Specifies if the skeleton should be serialized
  79918. */
  79919. this.doNotSerialize = false;
  79920. this._animationPropertiesOverride = null;
  79921. // Events
  79922. /**
  79923. * An observable triggered before computing the skeleton's matrices
  79924. */
  79925. this.onBeforeComputeObservable = new BABYLON.Observable();
  79926. this.bones = [];
  79927. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79928. scene.skeletons.push(this);
  79929. //make sure it will recalculate the matrix next time prepare is called.
  79930. this._isDirty = true;
  79931. }
  79932. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79933. /**
  79934. * Gets or sets the animation properties override
  79935. */
  79936. get: function () {
  79937. if (!this._animationPropertiesOverride) {
  79938. return this._scene.animationPropertiesOverride;
  79939. }
  79940. return this._animationPropertiesOverride;
  79941. },
  79942. set: function (value) {
  79943. this._animationPropertiesOverride = value;
  79944. },
  79945. enumerable: true,
  79946. configurable: true
  79947. });
  79948. // Members
  79949. /**
  79950. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79951. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79952. * @returns a Float32Array containing matrices data
  79953. */
  79954. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79955. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79956. return mesh._bonesTransformMatrices;
  79957. }
  79958. if (!this._transformMatrices) {
  79959. this.prepare();
  79960. }
  79961. return this._transformMatrices;
  79962. };
  79963. /**
  79964. * Gets the current hosting scene
  79965. * @returns a scene object
  79966. */
  79967. Skeleton.prototype.getScene = function () {
  79968. return this._scene;
  79969. };
  79970. // Methods
  79971. /**
  79972. * Gets a string representing the current skeleton data
  79973. * @param fullDetails defines a boolean indicating if we want a verbose version
  79974. * @returns a string representing the current skeleton data
  79975. */
  79976. Skeleton.prototype.toString = function (fullDetails) {
  79977. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79978. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79979. if (fullDetails) {
  79980. ret += ", Ranges: {";
  79981. var first = true;
  79982. for (var name_1 in this._ranges) {
  79983. if (first) {
  79984. ret += ", ";
  79985. first = false;
  79986. }
  79987. ret += name_1;
  79988. }
  79989. ret += "}";
  79990. }
  79991. return ret;
  79992. };
  79993. /**
  79994. * Get bone's index searching by name
  79995. * @param name defines bone's name to search for
  79996. * @return the indice of the bone. Returns -1 if not found
  79997. */
  79998. Skeleton.prototype.getBoneIndexByName = function (name) {
  79999. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80000. if (this.bones[boneIndex].name === name) {
  80001. return boneIndex;
  80002. }
  80003. }
  80004. return -1;
  80005. };
  80006. /**
  80007. * Creater a new animation range
  80008. * @param name defines the name of the range
  80009. * @param from defines the start key
  80010. * @param to defines the end key
  80011. */
  80012. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80013. // check name not already in use
  80014. if (!this._ranges[name]) {
  80015. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80016. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80017. if (this.bones[i].animations[0]) {
  80018. this.bones[i].animations[0].createRange(name, from, to);
  80019. }
  80020. }
  80021. }
  80022. };
  80023. /**
  80024. * Delete a specific animation range
  80025. * @param name defines the name of the range
  80026. * @param deleteFrames defines if frames must be removed as well
  80027. */
  80028. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80029. if (deleteFrames === void 0) { deleteFrames = true; }
  80030. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80031. if (this.bones[i].animations[0]) {
  80032. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80033. }
  80034. }
  80035. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80036. };
  80037. /**
  80038. * Gets a specific animation range
  80039. * @param name defines the name of the range to look for
  80040. * @returns the requested animation range or null if not found
  80041. */
  80042. Skeleton.prototype.getAnimationRange = function (name) {
  80043. return this._ranges[name];
  80044. };
  80045. /**
  80046. * Gets the list of all animation ranges defined on this skeleton
  80047. * @returns an array
  80048. */
  80049. Skeleton.prototype.getAnimationRanges = function () {
  80050. var animationRanges = [];
  80051. var name;
  80052. var i = 0;
  80053. for (name in this._ranges) {
  80054. animationRanges[i] = this._ranges[name];
  80055. i++;
  80056. }
  80057. return animationRanges;
  80058. };
  80059. /**
  80060. * Copy animation range from a source skeleton.
  80061. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80062. * @param source defines the source skeleton
  80063. * @param name defines the name of the range to copy
  80064. * @param rescaleAsRequired defines if rescaling must be applied if required
  80065. * @returns true if operation was successful
  80066. */
  80067. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80068. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80069. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80070. return false;
  80071. }
  80072. var ret = true;
  80073. var frameOffset = this._getHighestAnimationFrame() + 1;
  80074. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80075. var boneDict = {};
  80076. var sourceBones = source.bones;
  80077. var nBones;
  80078. var i;
  80079. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80080. boneDict[sourceBones[i].name] = sourceBones[i];
  80081. }
  80082. if (this.bones.length !== sourceBones.length) {
  80083. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80084. ret = false;
  80085. }
  80086. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80087. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80088. var boneName = this.bones[i].name;
  80089. var sourceBone = boneDict[boneName];
  80090. if (sourceBone) {
  80091. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80092. }
  80093. else {
  80094. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80095. ret = false;
  80096. }
  80097. }
  80098. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80099. var range = source.getAnimationRange(name);
  80100. if (range) {
  80101. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80102. }
  80103. return ret;
  80104. };
  80105. /**
  80106. * Forces the skeleton to go to rest pose
  80107. */
  80108. Skeleton.prototype.returnToRest = function () {
  80109. for (var index = 0; index < this.bones.length; index++) {
  80110. this.bones[index].returnToRest();
  80111. }
  80112. };
  80113. Skeleton.prototype._getHighestAnimationFrame = function () {
  80114. var ret = 0;
  80115. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80116. if (this.bones[i].animations[0]) {
  80117. var highest = this.bones[i].animations[0].getHighestFrame();
  80118. if (ret < highest) {
  80119. ret = highest;
  80120. }
  80121. }
  80122. }
  80123. return ret;
  80124. };
  80125. /**
  80126. * Begin a specific animation range
  80127. * @param name defines the name of the range to start
  80128. * @param loop defines if looping must be turned on (false by default)
  80129. * @param speedRatio defines the speed ratio to apply (1 by default)
  80130. * @param onAnimationEnd defines a callback which will be called when animation will end
  80131. * @returns a new animatable
  80132. */
  80133. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80134. var range = this.getAnimationRange(name);
  80135. if (!range) {
  80136. return null;
  80137. }
  80138. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80139. };
  80140. /** @hidden */
  80141. Skeleton.prototype._markAsDirty = function () {
  80142. this._isDirty = true;
  80143. };
  80144. /** @hidden */
  80145. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80146. this._meshesWithPoseMatrix.push(mesh);
  80147. };
  80148. /** @hidden */
  80149. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80150. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80151. if (index > -1) {
  80152. this._meshesWithPoseMatrix.splice(index, 1);
  80153. }
  80154. };
  80155. /** @hidden */
  80156. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80157. this.onBeforeComputeObservable.notifyObservers(this);
  80158. for (var index = 0; index < this.bones.length; index++) {
  80159. var bone = this.bones[index];
  80160. var parentBone = bone.getParent();
  80161. if (parentBone) {
  80162. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80163. }
  80164. else {
  80165. if (initialSkinMatrix) {
  80166. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80167. }
  80168. else {
  80169. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80170. }
  80171. }
  80172. if (bone._index !== -1) {
  80173. var mappedIndex = bone._index === null ? index : bone._index;
  80174. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80175. }
  80176. }
  80177. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80178. };
  80179. /**
  80180. * Build all resources required to render a skeleton
  80181. */
  80182. Skeleton.prototype.prepare = function () {
  80183. if (!this._isDirty) {
  80184. return;
  80185. }
  80186. if (this.needInitialSkinMatrix) {
  80187. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80188. var mesh = this._meshesWithPoseMatrix[index];
  80189. var poseMatrix = mesh.getPoseMatrix();
  80190. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80191. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80192. }
  80193. if (this._synchronizedWithMesh !== mesh) {
  80194. this._synchronizedWithMesh = mesh;
  80195. // Prepare bones
  80196. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80197. var bone = this.bones[boneIndex];
  80198. if (!bone.getParent()) {
  80199. var matrix = bone.getBaseMatrix();
  80200. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80201. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80202. }
  80203. }
  80204. }
  80205. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80206. }
  80207. }
  80208. else {
  80209. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80210. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80211. }
  80212. this._computeTransformMatrices(this._transformMatrices, null);
  80213. }
  80214. this._isDirty = false;
  80215. this._scene._activeBones.addCount(this.bones.length, false);
  80216. };
  80217. /**
  80218. * Gets the list of animatables currently running for this skeleton
  80219. * @returns an array of animatables
  80220. */
  80221. Skeleton.prototype.getAnimatables = function () {
  80222. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80223. this._animatables = [];
  80224. for (var index = 0; index < this.bones.length; index++) {
  80225. this._animatables.push(this.bones[index]);
  80226. }
  80227. }
  80228. return this._animatables;
  80229. };
  80230. /**
  80231. * Clone the current skeleton
  80232. * @param name defines the name of the new skeleton
  80233. * @param id defines the id of the enw skeleton
  80234. * @returns the new skeleton
  80235. */
  80236. Skeleton.prototype.clone = function (name, id) {
  80237. var result = new Skeleton(name, id || name, this._scene);
  80238. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80239. for (var index = 0; index < this.bones.length; index++) {
  80240. var source = this.bones[index];
  80241. var parentBone = null;
  80242. var parent_1 = source.getParent();
  80243. if (parent_1) {
  80244. var parentIndex = this.bones.indexOf(parent_1);
  80245. parentBone = result.bones[parentIndex];
  80246. }
  80247. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80248. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80249. }
  80250. if (this._ranges) {
  80251. result._ranges = {};
  80252. for (var rangeName in this._ranges) {
  80253. var range = this._ranges[rangeName];
  80254. if (range) {
  80255. result._ranges[rangeName] = range.clone();
  80256. }
  80257. }
  80258. }
  80259. this._isDirty = true;
  80260. return result;
  80261. };
  80262. /**
  80263. * Enable animation blending for this skeleton
  80264. * @param blendingSpeed defines the blending speed to apply
  80265. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80266. */
  80267. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80268. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80269. this.bones.forEach(function (bone) {
  80270. bone.animations.forEach(function (animation) {
  80271. animation.enableBlending = true;
  80272. animation.blendingSpeed = blendingSpeed;
  80273. });
  80274. });
  80275. };
  80276. /**
  80277. * Releases all resources associated with the current skeleton
  80278. */
  80279. Skeleton.prototype.dispose = function () {
  80280. this._meshesWithPoseMatrix = [];
  80281. // Animations
  80282. this.getScene().stopAnimation(this);
  80283. // Remove from scene
  80284. this.getScene().removeSkeleton(this);
  80285. };
  80286. /**
  80287. * Serialize the skeleton in a JSON object
  80288. * @returns a JSON object
  80289. */
  80290. Skeleton.prototype.serialize = function () {
  80291. var serializationObject = {};
  80292. serializationObject.name = this.name;
  80293. serializationObject.id = this.id;
  80294. if (this.dimensionsAtRest) {
  80295. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80296. }
  80297. serializationObject.bones = [];
  80298. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80299. for (var index = 0; index < this.bones.length; index++) {
  80300. var bone = this.bones[index];
  80301. var parent_2 = bone.getParent();
  80302. var serializedBone = {
  80303. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80304. name: bone.name,
  80305. matrix: bone.getBaseMatrix().toArray(),
  80306. rest: bone.getRestPose().toArray()
  80307. };
  80308. serializationObject.bones.push(serializedBone);
  80309. if (bone.length) {
  80310. serializedBone.length = bone.length;
  80311. }
  80312. if (bone.metadata) {
  80313. serializedBone.metadata = bone.metadata;
  80314. }
  80315. if (bone.animations && bone.animations.length > 0) {
  80316. serializedBone.animation = bone.animations[0].serialize();
  80317. }
  80318. serializationObject.ranges = [];
  80319. for (var name in this._ranges) {
  80320. var source = this._ranges[name];
  80321. if (!source) {
  80322. continue;
  80323. }
  80324. var range = {};
  80325. range.name = name;
  80326. range.from = source.from;
  80327. range.to = source.to;
  80328. serializationObject.ranges.push(range);
  80329. }
  80330. }
  80331. return serializationObject;
  80332. };
  80333. /**
  80334. * Creates a new skeleton from serialized data
  80335. * @param parsedSkeleton defines the serialized data
  80336. * @param scene defines the hosting scene
  80337. * @returns a new skeleton
  80338. */
  80339. Skeleton.Parse = function (parsedSkeleton, scene) {
  80340. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80341. if (parsedSkeleton.dimensionsAtRest) {
  80342. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80343. }
  80344. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80345. var index;
  80346. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80347. var parsedBone = parsedSkeleton.bones[index];
  80348. var parentBone = null;
  80349. if (parsedBone.parentBoneIndex > -1) {
  80350. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80351. }
  80352. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80353. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80354. if (parsedBone.length) {
  80355. bone.length = parsedBone.length;
  80356. }
  80357. if (parsedBone.metadata) {
  80358. bone.metadata = parsedBone.metadata;
  80359. }
  80360. if (parsedBone.animation) {
  80361. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80362. }
  80363. }
  80364. // placed after bones, so createAnimationRange can cascade down
  80365. if (parsedSkeleton.ranges) {
  80366. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80367. var data = parsedSkeleton.ranges[index];
  80368. skeleton.createAnimationRange(data.name, data.from, data.to);
  80369. }
  80370. }
  80371. return skeleton;
  80372. };
  80373. /**
  80374. * Compute all node absolute transforms
  80375. * @param forceUpdate defines if computation must be done even if cache is up to date
  80376. */
  80377. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80378. if (forceUpdate === void 0) { forceUpdate = false; }
  80379. var renderId = this._scene.getRenderId();
  80380. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80381. this.bones[0].computeAbsoluteTransforms();
  80382. this._lastAbsoluteTransformsUpdateId = renderId;
  80383. }
  80384. };
  80385. /**
  80386. * Gets the root pose matrix
  80387. * @returns a matrix
  80388. */
  80389. Skeleton.prototype.getPoseMatrix = function () {
  80390. var poseMatrix = null;
  80391. if (this._meshesWithPoseMatrix.length > 0) {
  80392. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80393. }
  80394. return poseMatrix;
  80395. };
  80396. /**
  80397. * Sorts bones per internal index
  80398. */
  80399. Skeleton.prototype.sortBones = function () {
  80400. var bones = new Array();
  80401. var visited = new Array(this.bones.length);
  80402. for (var index = 0; index < this.bones.length; index++) {
  80403. this._sortBones(index, bones, visited);
  80404. }
  80405. this.bones = bones;
  80406. };
  80407. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80408. if (visited[index]) {
  80409. return;
  80410. }
  80411. visited[index] = true;
  80412. var bone = this.bones[index];
  80413. if (bone._index === undefined) {
  80414. bone._index = index;
  80415. }
  80416. var parentBone = bone.getParent();
  80417. if (parentBone) {
  80418. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80419. }
  80420. bones.push(bone);
  80421. };
  80422. return Skeleton;
  80423. }());
  80424. BABYLON.Skeleton = Skeleton;
  80425. })(BABYLON || (BABYLON = {}));
  80426. //# sourceMappingURL=babylon.skeleton.js.map
  80427. var BABYLON;
  80428. (function (BABYLON) {
  80429. var SphericalPolynomial = /** @class */ (function () {
  80430. function SphericalPolynomial() {
  80431. this.x = BABYLON.Vector3.Zero();
  80432. this.y = BABYLON.Vector3.Zero();
  80433. this.z = BABYLON.Vector3.Zero();
  80434. this.xx = BABYLON.Vector3.Zero();
  80435. this.yy = BABYLON.Vector3.Zero();
  80436. this.zz = BABYLON.Vector3.Zero();
  80437. this.xy = BABYLON.Vector3.Zero();
  80438. this.yz = BABYLON.Vector3.Zero();
  80439. this.zx = BABYLON.Vector3.Zero();
  80440. }
  80441. SphericalPolynomial.prototype.addAmbient = function (color) {
  80442. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80443. this.xx = this.xx.add(colorVector);
  80444. this.yy = this.yy.add(colorVector);
  80445. this.zz = this.zz.add(colorVector);
  80446. };
  80447. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80448. var result = new SphericalPolynomial();
  80449. result.x = harmonics.L11.scale(1.02333);
  80450. result.y = harmonics.L1_1.scale(1.02333);
  80451. result.z = harmonics.L10.scale(1.02333);
  80452. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80453. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80454. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80455. result.yz = harmonics.L2_1.scale(0.858086);
  80456. result.zx = harmonics.L21.scale(0.858086);
  80457. result.xy = harmonics.L2_2.scale(0.858086);
  80458. result.scale(1.0 / Math.PI);
  80459. return result;
  80460. };
  80461. SphericalPolynomial.prototype.scale = function (scale) {
  80462. this.x = this.x.scale(scale);
  80463. this.y = this.y.scale(scale);
  80464. this.z = this.z.scale(scale);
  80465. this.xx = this.xx.scale(scale);
  80466. this.yy = this.yy.scale(scale);
  80467. this.zz = this.zz.scale(scale);
  80468. this.yz = this.yz.scale(scale);
  80469. this.zx = this.zx.scale(scale);
  80470. this.xy = this.xy.scale(scale);
  80471. };
  80472. return SphericalPolynomial;
  80473. }());
  80474. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80475. var SphericalHarmonics = /** @class */ (function () {
  80476. function SphericalHarmonics() {
  80477. this.L00 = BABYLON.Vector3.Zero();
  80478. this.L1_1 = BABYLON.Vector3.Zero();
  80479. this.L10 = BABYLON.Vector3.Zero();
  80480. this.L11 = BABYLON.Vector3.Zero();
  80481. this.L2_2 = BABYLON.Vector3.Zero();
  80482. this.L2_1 = BABYLON.Vector3.Zero();
  80483. this.L20 = BABYLON.Vector3.Zero();
  80484. this.L21 = BABYLON.Vector3.Zero();
  80485. this.L22 = BABYLON.Vector3.Zero();
  80486. }
  80487. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80488. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80489. var c = colorVector.scale(deltaSolidAngle);
  80490. this.L00 = this.L00.add(c.scale(0.282095));
  80491. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80492. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80493. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80494. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80495. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80496. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80497. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80498. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80499. };
  80500. SphericalHarmonics.prototype.scale = function (scale) {
  80501. this.L00 = this.L00.scale(scale);
  80502. this.L1_1 = this.L1_1.scale(scale);
  80503. this.L10 = this.L10.scale(scale);
  80504. this.L11 = this.L11.scale(scale);
  80505. this.L2_2 = this.L2_2.scale(scale);
  80506. this.L2_1 = this.L2_1.scale(scale);
  80507. this.L20 = this.L20.scale(scale);
  80508. this.L21 = this.L21.scale(scale);
  80509. this.L22 = this.L22.scale(scale);
  80510. };
  80511. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80512. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80513. //
  80514. // E_lm = A_l * L_lm
  80515. //
  80516. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80517. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80518. // the scaling factors are given in equation 9.
  80519. // Constant (Band 0)
  80520. this.L00 = this.L00.scale(3.141593);
  80521. // Linear (Band 1)
  80522. this.L1_1 = this.L1_1.scale(2.094395);
  80523. this.L10 = this.L10.scale(2.094395);
  80524. this.L11 = this.L11.scale(2.094395);
  80525. // Quadratic (Band 2)
  80526. this.L2_2 = this.L2_2.scale(0.785398);
  80527. this.L2_1 = this.L2_1.scale(0.785398);
  80528. this.L20 = this.L20.scale(0.785398);
  80529. this.L21 = this.L21.scale(0.785398);
  80530. this.L22 = this.L22.scale(0.785398);
  80531. };
  80532. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80533. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80534. // L = (1/pi) * E * rho
  80535. //
  80536. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80537. this.scale(1.0 / Math.PI);
  80538. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80539. // (The pixel shader must apply albedo after texture fetches, etc).
  80540. };
  80541. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80542. var result = new SphericalHarmonics();
  80543. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80544. result.L1_1 = polynomial.y.scale(0.977204);
  80545. result.L10 = polynomial.z.scale(0.977204);
  80546. result.L11 = polynomial.x.scale(0.977204);
  80547. result.L2_2 = polynomial.xy.scale(1.16538);
  80548. result.L2_1 = polynomial.yz.scale(1.16538);
  80549. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80550. result.L21 = polynomial.zx.scale(1.16538);
  80551. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80552. result.scale(Math.PI);
  80553. return result;
  80554. };
  80555. return SphericalHarmonics;
  80556. }());
  80557. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80558. })(BABYLON || (BABYLON = {}));
  80559. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80560. var BABYLON;
  80561. (function (BABYLON) {
  80562. var FileFaceOrientation = /** @class */ (function () {
  80563. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80564. this.name = name;
  80565. this.worldAxisForNormal = worldAxisForNormal;
  80566. this.worldAxisForFileX = worldAxisForFileX;
  80567. this.worldAxisForFileY = worldAxisForFileY;
  80568. }
  80569. return FileFaceOrientation;
  80570. }());
  80571. ;
  80572. /**
  80573. * Helper class dealing with the extraction of spherical polynomial dataArray
  80574. * from a cube map.
  80575. */
  80576. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80577. function CubeMapToSphericalPolynomialTools() {
  80578. }
  80579. /**
  80580. * Converts a texture to the according Spherical Polynomial data.
  80581. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80582. *
  80583. * @param texture The texture to extract the information from.
  80584. * @return The Spherical Polynomial data.
  80585. */
  80586. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80587. if (!texture.isCube) {
  80588. // Only supports cube Textures currently.
  80589. return null;
  80590. }
  80591. var size = texture.getSize().width;
  80592. var right = texture.readPixels(0);
  80593. var left = texture.readPixels(1);
  80594. var up;
  80595. var down;
  80596. if (texture.isRenderTarget) {
  80597. up = texture.readPixels(3);
  80598. down = texture.readPixels(2);
  80599. }
  80600. else {
  80601. up = texture.readPixels(2);
  80602. down = texture.readPixels(3);
  80603. }
  80604. var front = texture.readPixels(4);
  80605. var back = texture.readPixels(5);
  80606. var gammaSpace = texture.gammaSpace;
  80607. // Always read as RGBA.
  80608. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80609. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80610. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80611. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80612. }
  80613. var cubeInfo = {
  80614. size: size,
  80615. right: right,
  80616. left: left,
  80617. up: up,
  80618. down: down,
  80619. front: front,
  80620. back: back,
  80621. format: format,
  80622. type: type,
  80623. gammaSpace: gammaSpace,
  80624. };
  80625. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80626. };
  80627. /**
  80628. * Converts a cubemap to the according Spherical Polynomial data.
  80629. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80630. *
  80631. * @param cubeInfo The Cube map to extract the information from.
  80632. * @return The Spherical Polynomial data.
  80633. */
  80634. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80635. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80636. var totalSolidAngle = 0.0;
  80637. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80638. var du = 2.0 / cubeInfo.size;
  80639. var dv = du;
  80640. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80641. var minUV = du * 0.5 - 1.0;
  80642. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80643. var fileFace = this.FileFaces[faceIndex];
  80644. var dataArray = cubeInfo[fileFace.name];
  80645. var v = minUV;
  80646. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80647. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80648. // Because SP is still linear, so summation is fine in that basis.
  80649. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80650. for (var y = 0; y < cubeInfo.size; y++) {
  80651. var u = minUV;
  80652. for (var x = 0; x < cubeInfo.size; x++) {
  80653. // World direction (not normalised)
  80654. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80655. worldDirection.normalize();
  80656. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80657. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80658. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80659. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80660. // Handle Integer types.
  80661. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80662. r /= 255;
  80663. g /= 255;
  80664. b /= 255;
  80665. }
  80666. // Handle Gamma space textures.
  80667. if (cubeInfo.gammaSpace) {
  80668. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80669. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80670. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80671. }
  80672. var color = new BABYLON.Color3(r, g, b);
  80673. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80674. totalSolidAngle += deltaSolidAngle;
  80675. u += du;
  80676. }
  80677. v += dv;
  80678. }
  80679. }
  80680. // Solid angle for entire sphere is 4*pi
  80681. var sphereSolidAngle = 4.0 * Math.PI;
  80682. // Adjust the solid angle to allow for how many faces we processed.
  80683. var facesProcessed = 6.0;
  80684. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80685. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80686. // This is needed because the numerical integration over the cube uses a
  80687. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80688. // and also to compensate for accumulative error due to float precision in the summation.
  80689. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80690. sphericalHarmonics.scale(correctionFactor);
  80691. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80692. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80693. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80694. };
  80695. CubeMapToSphericalPolynomialTools.FileFaces = [
  80696. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80697. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80698. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80699. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80700. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80701. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80702. ];
  80703. return CubeMapToSphericalPolynomialTools;
  80704. }());
  80705. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80706. })(BABYLON || (BABYLON = {}));
  80707. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80708. var BABYLON;
  80709. (function (BABYLON) {
  80710. /**
  80711. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80712. */
  80713. var PanoramaToCubeMapTools = /** @class */ (function () {
  80714. function PanoramaToCubeMapTools() {
  80715. }
  80716. /**
  80717. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80718. *
  80719. * @param float32Array The source data.
  80720. * @param inputWidth The width of the input panorama.
  80721. * @param inputhHeight The height of the input panorama.
  80722. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80723. * @return The cubemap data
  80724. */
  80725. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80726. if (!float32Array) {
  80727. throw "ConvertPanoramaToCubemap: input cannot be null";
  80728. }
  80729. if (float32Array.length != inputWidth * inputHeight * 3) {
  80730. throw "ConvertPanoramaToCubemap: input size is wrong";
  80731. }
  80732. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80733. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80734. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80735. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80736. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80737. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80738. return {
  80739. front: textureFront,
  80740. back: textureBack,
  80741. left: textureLeft,
  80742. right: textureRight,
  80743. up: textureUp,
  80744. down: textureDown,
  80745. size: size,
  80746. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80747. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80748. gammaSpace: false,
  80749. };
  80750. };
  80751. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80752. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80753. var textureArray = new Float32Array(buffer);
  80754. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80755. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80756. var dy = 1 / texSize;
  80757. var fy = 0;
  80758. for (var y = 0; y < texSize; y++) {
  80759. var xv1 = faceData[0];
  80760. var xv2 = faceData[2];
  80761. for (var x = 0; x < texSize; x++) {
  80762. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80763. v.normalize();
  80764. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80765. // 3 channels per pixels
  80766. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80767. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80768. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80769. xv1 = xv1.add(rotDX1);
  80770. xv2 = xv2.add(rotDX2);
  80771. }
  80772. fy += dy;
  80773. }
  80774. return textureArray;
  80775. };
  80776. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80777. var theta = Math.atan2(vDir.z, vDir.x);
  80778. var phi = Math.acos(vDir.y);
  80779. while (theta < -Math.PI)
  80780. theta += 2 * Math.PI;
  80781. while (theta > Math.PI)
  80782. theta -= 2 * Math.PI;
  80783. var dx = theta / Math.PI;
  80784. var dy = phi / Math.PI;
  80785. // recenter.
  80786. dx = dx * 0.5 + 0.5;
  80787. var px = Math.round(dx * inputWidth);
  80788. if (px < 0)
  80789. px = 0;
  80790. else if (px >= inputWidth)
  80791. px = inputWidth - 1;
  80792. var py = Math.round(dy * inputHeight);
  80793. if (py < 0)
  80794. py = 0;
  80795. else if (py >= inputHeight)
  80796. py = inputHeight - 1;
  80797. var inputY = (inputHeight - py - 1);
  80798. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80799. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80800. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80801. return {
  80802. r: r,
  80803. g: g,
  80804. b: b
  80805. };
  80806. };
  80807. PanoramaToCubeMapTools.FACE_FRONT = [
  80808. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80809. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80810. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80811. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80812. ];
  80813. PanoramaToCubeMapTools.FACE_BACK = [
  80814. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80815. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80816. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80817. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80818. ];
  80819. PanoramaToCubeMapTools.FACE_RIGHT = [
  80820. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80821. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80822. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80823. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80824. ];
  80825. PanoramaToCubeMapTools.FACE_LEFT = [
  80826. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80827. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80828. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80829. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80830. ];
  80831. PanoramaToCubeMapTools.FACE_DOWN = [
  80832. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80833. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80834. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80835. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80836. ];
  80837. PanoramaToCubeMapTools.FACE_UP = [
  80838. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80839. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80840. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80841. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80842. ];
  80843. return PanoramaToCubeMapTools;
  80844. }());
  80845. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80846. })(BABYLON || (BABYLON = {}));
  80847. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80848. var BABYLON;
  80849. (function (BABYLON) {
  80850. ;
  80851. /**
  80852. * This groups tools to convert HDR texture to native colors array.
  80853. */
  80854. var HDRTools = /** @class */ (function () {
  80855. function HDRTools() {
  80856. }
  80857. HDRTools.Ldexp = function (mantissa, exponent) {
  80858. if (exponent > 1023) {
  80859. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80860. }
  80861. if (exponent < -1074) {
  80862. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80863. }
  80864. return mantissa * Math.pow(2, exponent);
  80865. };
  80866. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80867. if (exponent > 0) { /*nonzero pixel*/
  80868. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80869. float32array[index + 0] = red * exponent;
  80870. float32array[index + 1] = green * exponent;
  80871. float32array[index + 2] = blue * exponent;
  80872. }
  80873. else {
  80874. float32array[index + 0] = 0;
  80875. float32array[index + 1] = 0;
  80876. float32array[index + 2] = 0;
  80877. }
  80878. };
  80879. HDRTools.readStringLine = function (uint8array, startIndex) {
  80880. var line = "";
  80881. var character = "";
  80882. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80883. character = String.fromCharCode(uint8array[i]);
  80884. if (character == "\n") {
  80885. break;
  80886. }
  80887. line += character;
  80888. }
  80889. return line;
  80890. };
  80891. /**
  80892. * Reads header information from an RGBE texture stored in a native array.
  80893. * More information on this format are available here:
  80894. * https://en.wikipedia.org/wiki/RGBE_image_format
  80895. *
  80896. * @param uint8array The binary file stored in native array.
  80897. * @return The header information.
  80898. */
  80899. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80900. var height = 0;
  80901. var width = 0;
  80902. var line = this.readStringLine(uint8array, 0);
  80903. if (line[0] != '#' || line[1] != '?') {
  80904. throw "Bad HDR Format.";
  80905. }
  80906. var endOfHeader = false;
  80907. var findFormat = false;
  80908. var lineIndex = 0;
  80909. do {
  80910. lineIndex += (line.length + 1);
  80911. line = this.readStringLine(uint8array, lineIndex);
  80912. if (line == "FORMAT=32-bit_rle_rgbe") {
  80913. findFormat = true;
  80914. }
  80915. else if (line.length == 0) {
  80916. endOfHeader = true;
  80917. }
  80918. } while (!endOfHeader);
  80919. if (!findFormat) {
  80920. throw "HDR Bad header format, unsupported FORMAT";
  80921. }
  80922. lineIndex += (line.length + 1);
  80923. line = this.readStringLine(uint8array, lineIndex);
  80924. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80925. var match = sizeRegexp.exec(line);
  80926. // TODO. Support +Y and -X if needed.
  80927. if (!match || match.length < 3) {
  80928. throw "HDR Bad header format, no size";
  80929. }
  80930. width = parseInt(match[2]);
  80931. height = parseInt(match[1]);
  80932. if (width < 8 || width > 0x7fff) {
  80933. throw "HDR Bad header format, unsupported size";
  80934. }
  80935. lineIndex += (line.length + 1);
  80936. return {
  80937. height: height,
  80938. width: width,
  80939. dataPosition: lineIndex
  80940. };
  80941. };
  80942. /**
  80943. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80944. * This RGBE texture needs to store the information as a panorama.
  80945. *
  80946. * More information on this format are available here:
  80947. * https://en.wikipedia.org/wiki/RGBE_image_format
  80948. *
  80949. * @param buffer The binary file stored in an array buffer.
  80950. * @param size The expected size of the extracted cubemap.
  80951. * @return The Cube Map information.
  80952. */
  80953. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80954. var uint8array = new Uint8Array(buffer);
  80955. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80956. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80957. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80958. return cubeMapData;
  80959. };
  80960. /**
  80961. * Returns the pixels data extracted from an RGBE texture.
  80962. * This pixels will be stored left to right up to down in the R G B order in one array.
  80963. *
  80964. * More information on this format are available here:
  80965. * https://en.wikipedia.org/wiki/RGBE_image_format
  80966. *
  80967. * @param uint8array The binary file stored in an array buffer.
  80968. * @param hdrInfo The header information of the file.
  80969. * @return The pixels data in RGB right to left up to down order.
  80970. */
  80971. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80972. // Keep for multi format supports.
  80973. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80974. };
  80975. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80976. var num_scanlines = hdrInfo.height;
  80977. var scanline_width = hdrInfo.width;
  80978. var a, b, c, d, count;
  80979. var dataIndex = hdrInfo.dataPosition;
  80980. var index = 0, endIndex = 0, i = 0;
  80981. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80982. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80983. // 3 channels of 4 bytes per pixel in float.
  80984. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80985. var resultArray = new Float32Array(resultBuffer);
  80986. // read in each successive scanline
  80987. while (num_scanlines > 0) {
  80988. a = uint8array[dataIndex++];
  80989. b = uint8array[dataIndex++];
  80990. c = uint8array[dataIndex++];
  80991. d = uint8array[dataIndex++];
  80992. if (a != 2 || b != 2 || (c & 0x80)) {
  80993. // this file is not run length encoded
  80994. throw "HDR Bad header format, not RLE";
  80995. }
  80996. if (((c << 8) | d) != scanline_width) {
  80997. throw "HDR Bad header format, wrong scan line width";
  80998. }
  80999. index = 0;
  81000. // read each of the four channels for the scanline into the buffer
  81001. for (i = 0; i < 4; i++) {
  81002. endIndex = (i + 1) * scanline_width;
  81003. while (index < endIndex) {
  81004. a = uint8array[dataIndex++];
  81005. b = uint8array[dataIndex++];
  81006. if (a > 128) {
  81007. // a run of the same value
  81008. count = a - 128;
  81009. if ((count == 0) || (count > endIndex - index)) {
  81010. throw "HDR Bad Format, bad scanline data (run)";
  81011. }
  81012. while (count-- > 0) {
  81013. scanLineArray[index++] = b;
  81014. }
  81015. }
  81016. else {
  81017. // a non-run
  81018. count = a;
  81019. if ((count == 0) || (count > endIndex - index)) {
  81020. throw "HDR Bad Format, bad scanline data (non-run)";
  81021. }
  81022. scanLineArray[index++] = b;
  81023. if (--count > 0) {
  81024. for (var j = 0; j < count; j++) {
  81025. scanLineArray[index++] = uint8array[dataIndex++];
  81026. }
  81027. }
  81028. }
  81029. }
  81030. }
  81031. // now convert data from buffer into floats
  81032. for (i = 0; i < scanline_width; i++) {
  81033. a = scanLineArray[i];
  81034. b = scanLineArray[i + scanline_width];
  81035. c = scanLineArray[i + 2 * scanline_width];
  81036. d = scanLineArray[i + 3 * scanline_width];
  81037. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81038. }
  81039. num_scanlines--;
  81040. }
  81041. return resultArray;
  81042. };
  81043. return HDRTools;
  81044. }());
  81045. BABYLON.HDRTools = HDRTools;
  81046. })(BABYLON || (BABYLON = {}));
  81047. //# sourceMappingURL=babylon.hdr.js.map
  81048. var BABYLON;
  81049. (function (BABYLON) {
  81050. /**
  81051. * Sets of helpers addressing the serialization and deserialization of environment texture
  81052. * stored in a BabylonJS env file.
  81053. * Those files are usually stored as .env files.
  81054. */
  81055. var EnvironmentTextureTools = /** @class */ (function () {
  81056. function EnvironmentTextureTools() {
  81057. }
  81058. /**
  81059. * Gets the environment info from an env file.
  81060. * @param data The array buffer containing the .env bytes.
  81061. * @returns the environment file info (the json header) if successfully parsed.
  81062. */
  81063. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81064. var dataView = new DataView(data);
  81065. var pos = 0;
  81066. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81067. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81068. BABYLON.Tools.Error('Not a babylon environment map');
  81069. return null;
  81070. }
  81071. }
  81072. // Read json manifest - collect characters up to null terminator
  81073. var manifestString = '';
  81074. var charCode = 0x00;
  81075. while ((charCode = dataView.getUint8(pos++))) {
  81076. manifestString += String.fromCharCode(charCode);
  81077. }
  81078. var manifest = JSON.parse(manifestString);
  81079. if (manifest.specular) {
  81080. // Extend the header with the position of the payload.
  81081. manifest.specular.specularDataPosition = pos;
  81082. }
  81083. return manifest;
  81084. };
  81085. /**
  81086. * Creates an environment texture from a loaded cube texture.
  81087. * @param texture defines the cube texture to convert in env file
  81088. * @return a promise containing the environment data if succesfull.
  81089. */
  81090. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81091. var _this = this;
  81092. var internalTexture = texture.getInternalTexture();
  81093. if (!internalTexture) {
  81094. return Promise.reject("The cube texture is invalid.");
  81095. }
  81096. if (!texture._prefiltered) {
  81097. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81098. }
  81099. var engine = internalTexture.getEngine();
  81100. if (engine && engine.premultipliedAlpha) {
  81101. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81102. }
  81103. var canvas = engine.getRenderingCanvas();
  81104. if (!canvas) {
  81105. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81106. }
  81107. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81108. if (!engine.getCaps().textureFloatRender) {
  81109. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81110. if (!engine.getCaps().textureHalfFloatRender) {
  81111. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81112. }
  81113. }
  81114. var cubeWidth = internalTexture.width;
  81115. var hostingScene = new BABYLON.Scene(engine);
  81116. var specularTextures = {};
  81117. var promises = [];
  81118. // Read and collect all mipmaps data from the cube.
  81119. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81120. mipmapsCount = Math.round(mipmapsCount);
  81121. var _loop_1 = function (i) {
  81122. var faceWidth = Math.pow(2, mipmapsCount - i);
  81123. var _loop_2 = function (face) {
  81124. var data = texture.readPixels(face, i);
  81125. // Creates a temp texture with the face data.
  81126. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81127. // And rgbdEncode them.
  81128. var promise = new Promise(function (resolve, reject) {
  81129. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81130. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81131. rgbdPostProcess.onApply = function (effect) {
  81132. effect._bindTexture("textureSampler", tempTexture);
  81133. };
  81134. // As the process needs to happen on the main canvas, keep track of the current size
  81135. var currentW = engine.getRenderWidth();
  81136. var currentH = engine.getRenderHeight();
  81137. // Set the desired size for the texture
  81138. engine.setSize(faceWidth, faceWidth);
  81139. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81140. // Reading datas from WebGL
  81141. canvas.toBlob(function (blob) {
  81142. var fileReader = new FileReader();
  81143. fileReader.onload = function (event) {
  81144. var arrayBuffer = event.target.result;
  81145. specularTextures[i * 6 + face] = arrayBuffer;
  81146. resolve();
  81147. };
  81148. fileReader.readAsArrayBuffer(blob);
  81149. });
  81150. // Reapply the previous canvas size
  81151. engine.setSize(currentW, currentH);
  81152. });
  81153. });
  81154. promises.push(promise);
  81155. };
  81156. // All faces of the cube.
  81157. for (var face = 0; face < 6; face++) {
  81158. _loop_2(face);
  81159. }
  81160. };
  81161. for (var i = 0; i <= mipmapsCount; i++) {
  81162. _loop_1(i);
  81163. }
  81164. // Once all the textures haves been collected as RGBD stored in PNGs
  81165. return Promise.all(promises).then(function () {
  81166. // We can delete the hosting scene keeping track of all the creation objects
  81167. hostingScene.dispose();
  81168. // Creates the json header for the env texture
  81169. var info = {
  81170. version: 1,
  81171. width: cubeWidth,
  81172. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81173. specular: {
  81174. mipmaps: []
  81175. }
  81176. };
  81177. // Sets the specular image data information
  81178. var position = 0;
  81179. for (var i = 0; i <= mipmapsCount; i++) {
  81180. for (var face = 0; face < 6; face++) {
  81181. var byteLength = specularTextures[i * 6 + face].byteLength;
  81182. info.specular.mipmaps.push({
  81183. length: byteLength,
  81184. position: position
  81185. });
  81186. position += byteLength;
  81187. }
  81188. }
  81189. // Encode the JSON as an array buffer
  81190. var infoString = JSON.stringify(info);
  81191. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81192. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81193. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81194. infoView[i] = infoString.charCodeAt(i);
  81195. }
  81196. // Ends up with a null terminator for easier parsing
  81197. infoView[infoString.length] = 0x00;
  81198. // Computes the final required size and creates the storage
  81199. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81200. var finalBuffer = new ArrayBuffer(totalSize);
  81201. var finalBufferView = new Uint8Array(finalBuffer);
  81202. var dataView = new DataView(finalBuffer);
  81203. // Copy the magic bytes identifying the file in
  81204. var pos = 0;
  81205. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81206. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81207. }
  81208. // Add the json info
  81209. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81210. pos += infoBuffer.byteLength;
  81211. // Finally inserts the texture data
  81212. for (var i = 0; i <= mipmapsCount; i++) {
  81213. for (var face = 0; face < 6; face++) {
  81214. var dataBuffer = specularTextures[i * 6 + face];
  81215. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81216. pos += dataBuffer.byteLength;
  81217. }
  81218. }
  81219. // Voila
  81220. return finalBuffer;
  81221. });
  81222. };
  81223. /**
  81224. * Creates a JSON representation of the spherical data.
  81225. * @param texture defines the texture containing the polynomials
  81226. * @return the JSON representation of the spherical info
  81227. */
  81228. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81229. var polynmials = texture.sphericalPolynomial;
  81230. if (polynmials == null) {
  81231. return null;
  81232. }
  81233. return {
  81234. polynomials: true,
  81235. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81236. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81237. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81238. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81239. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81240. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81241. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81242. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81243. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81244. };
  81245. };
  81246. /**
  81247. * Uploads the texture info contained in the env file to te GPU.
  81248. * @param texture defines the internal texture to upload to
  81249. * @param arrayBuffer defines the buffer cotaining the data to load
  81250. * @param info defines the texture info retrieved through the GetEnvInfo method
  81251. * @returns a promise
  81252. */
  81253. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81254. if (info.version !== 1) {
  81255. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81256. }
  81257. var specularInfo = info.specular;
  81258. if (!specularInfo) {
  81259. // Nothing else parsed so far
  81260. return Promise.resolve();
  81261. }
  81262. // Double checks the enclosed info
  81263. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81264. mipmapsCount = Math.round(mipmapsCount) + 1;
  81265. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81266. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81267. }
  81268. // Gets everything ready.
  81269. var engine = texture.getEngine();
  81270. var expandTexture = false;
  81271. var generateNonLODTextures = false;
  81272. var rgbdPostProcess = null;
  81273. var cubeRtt = null;
  81274. var lodTextures = null;
  81275. var caps = engine.getCaps();
  81276. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81277. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81278. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81279. // Add extra process if texture lod is not supported
  81280. if (!caps.textureLOD) {
  81281. expandTexture = false;
  81282. generateNonLODTextures = true;
  81283. lodTextures = {};
  81284. }
  81285. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81286. else if (engine.webGLVersion < 2) {
  81287. expandTexture = false;
  81288. }
  81289. // If half float available we can uncompress the texture
  81290. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81291. expandTexture = true;
  81292. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81293. }
  81294. // If full float available we can uncompress the texture
  81295. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81296. expandTexture = true;
  81297. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81298. }
  81299. // Expand the texture if possible
  81300. if (expandTexture) {
  81301. // Simply run through the decode PP
  81302. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81303. texture._isRGBD = false;
  81304. texture.invertY = false;
  81305. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81306. generateDepthBuffer: false,
  81307. generateMipMaps: true,
  81308. generateStencilBuffer: false,
  81309. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81310. type: texture.type,
  81311. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81312. });
  81313. }
  81314. else {
  81315. texture._isRGBD = true;
  81316. texture.invertY = true;
  81317. // In case of missing support, applies the same patch than DDS files.
  81318. if (generateNonLODTextures) {
  81319. var mipSlices = 3;
  81320. var scale = texture._lodGenerationScale;
  81321. var offset = texture._lodGenerationOffset;
  81322. for (var i = 0; i < mipSlices; i++) {
  81323. //compute LOD from even spacing in smoothness (matching shader calculation)
  81324. var smoothness = i / (mipSlices - 1);
  81325. var roughness = 1 - smoothness;
  81326. var minLODIndex = offset; // roughness = 0
  81327. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81328. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81329. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81330. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81331. glTextureFromLod.isCube = true;
  81332. glTextureFromLod.invertY = true;
  81333. glTextureFromLod.generateMipMaps = false;
  81334. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81335. // Wrap in a base texture for easy binding.
  81336. var lodTexture = new BABYLON.BaseTexture(null);
  81337. lodTexture.isCube = true;
  81338. lodTexture._texture = glTextureFromLod;
  81339. lodTextures[mipmapIndex] = lodTexture;
  81340. switch (i) {
  81341. case 0:
  81342. texture._lodTextureLow = lodTexture;
  81343. break;
  81344. case 1:
  81345. texture._lodTextureMid = lodTexture;
  81346. break;
  81347. case 2:
  81348. texture._lodTextureHigh = lodTexture;
  81349. break;
  81350. }
  81351. }
  81352. }
  81353. }
  81354. var promises = [];
  81355. var _loop_3 = function (i) {
  81356. var _loop_4 = function (face) {
  81357. // Retrieves the face data
  81358. var imageData = specularInfo.mipmaps[i * 6 + face];
  81359. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81360. // Constructs an image element from bytes
  81361. var blob = new Blob([bytes], { type: 'image/png' });
  81362. var url = URL.createObjectURL(blob);
  81363. var image = new Image();
  81364. image.src = url;
  81365. // Enqueue promise to upload to the texture.
  81366. var promise = new Promise(function (resolve, reject) {
  81367. ;
  81368. image.onload = function () {
  81369. if (expandTexture) {
  81370. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81371. reject(message);
  81372. }, image);
  81373. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81374. // Uncompress the data to a RTT
  81375. rgbdPostProcess.onApply = function (effect) {
  81376. effect._bindTexture("textureSampler", tempTexture_1);
  81377. effect.setFloat2("scale", 1, 1);
  81378. };
  81379. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81380. // Cleanup
  81381. engine.restoreDefaultFramebuffer();
  81382. tempTexture_1.dispose();
  81383. window.URL.revokeObjectURL(url);
  81384. resolve();
  81385. });
  81386. }
  81387. else {
  81388. engine._uploadImageToTexture(texture, face, i, image);
  81389. // Upload the face to the none lod texture support
  81390. if (generateNonLODTextures) {
  81391. var lodTexture = lodTextures[i];
  81392. if (lodTexture) {
  81393. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81394. }
  81395. }
  81396. resolve();
  81397. }
  81398. };
  81399. image.onerror = function (error) {
  81400. reject(error);
  81401. };
  81402. });
  81403. promises.push(promise);
  81404. };
  81405. // All faces
  81406. for (var face = 0; face < 6; face++) {
  81407. _loop_4(face);
  81408. }
  81409. };
  81410. // All mipmaps
  81411. for (var i = 0; i < mipmapsCount; i++) {
  81412. _loop_3(i);
  81413. }
  81414. // Once all done, finishes the cleanup and return
  81415. return Promise.all(promises).then(function () {
  81416. // Relase temp RTT.
  81417. if (cubeRtt) {
  81418. engine._releaseFramebufferObjects(cubeRtt);
  81419. cubeRtt._swapAndDie(texture);
  81420. }
  81421. // Relase temp Post Process.
  81422. if (rgbdPostProcess) {
  81423. rgbdPostProcess.dispose();
  81424. }
  81425. // Flag internal texture as ready in case they are in use.
  81426. if (generateNonLODTextures) {
  81427. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81428. texture._lodTextureHigh._texture.isReady = true;
  81429. }
  81430. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81431. texture._lodTextureMid._texture.isReady = true;
  81432. }
  81433. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81434. texture._lodTextureLow._texture.isReady = true;
  81435. }
  81436. }
  81437. });
  81438. };
  81439. /**
  81440. * Uploads spherical polynomials information to the texture.
  81441. * @param texture defines the texture we are trying to upload the information to
  81442. * @param arrayBuffer defines the array buffer holding the data
  81443. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81444. */
  81445. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81446. if (info.version !== 1) {
  81447. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81448. }
  81449. var irradianceInfo = info.irradiance;
  81450. if (!irradianceInfo) {
  81451. return;
  81452. }
  81453. //harmonics now represent radiance
  81454. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81455. if (irradianceInfo.polynomials) {
  81456. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81457. }
  81458. else {
  81459. // convert From SH to SP.
  81460. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81461. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81462. }
  81463. };
  81464. /**
  81465. * Upload spherical polynomial coefficients to the texture
  81466. * @param polynmials Spherical polynmial coefficients (9)
  81467. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81468. */
  81469. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81470. outPolynomialCoefficents.x.x = polynmials.x[0];
  81471. outPolynomialCoefficents.x.y = polynmials.x[1];
  81472. outPolynomialCoefficents.x.z = polynmials.x[2];
  81473. outPolynomialCoefficents.y.x = polynmials.y[0];
  81474. outPolynomialCoefficents.y.y = polynmials.y[1];
  81475. outPolynomialCoefficents.y.z = polynmials.y[2];
  81476. outPolynomialCoefficents.z.x = polynmials.z[0];
  81477. outPolynomialCoefficents.z.y = polynmials.z[1];
  81478. outPolynomialCoefficents.z.z = polynmials.z[2];
  81479. //xx
  81480. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81481. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81482. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81483. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81484. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81485. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81486. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81487. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81488. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81489. //yz
  81490. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81491. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81492. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81493. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81494. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81495. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81496. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81497. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81498. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81499. };
  81500. /**
  81501. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81502. * L = (1/pi) * E * rho
  81503. *
  81504. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81505. * @param harmonics Spherical harmonic coefficients (9)
  81506. */
  81507. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81508. var scaleFactor = 1 / Math.PI;
  81509. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81510. // (The pixel shader must apply albedo after texture fetches, etc).
  81511. harmonics.l00[0] *= scaleFactor;
  81512. harmonics.l00[1] *= scaleFactor;
  81513. harmonics.l00[2] *= scaleFactor;
  81514. harmonics.l1_1[0] *= scaleFactor;
  81515. harmonics.l1_1[1] *= scaleFactor;
  81516. harmonics.l1_1[2] *= scaleFactor;
  81517. harmonics.l10[0] *= scaleFactor;
  81518. harmonics.l10[1] *= scaleFactor;
  81519. harmonics.l10[2] *= scaleFactor;
  81520. harmonics.l11[0] *= scaleFactor;
  81521. harmonics.l11[1] *= scaleFactor;
  81522. harmonics.l11[2] *= scaleFactor;
  81523. harmonics.l2_2[0] *= scaleFactor;
  81524. harmonics.l2_2[1] *= scaleFactor;
  81525. harmonics.l2_2[2] *= scaleFactor;
  81526. harmonics.l2_1[0] *= scaleFactor;
  81527. harmonics.l2_1[1] *= scaleFactor;
  81528. harmonics.l2_1[2] *= scaleFactor;
  81529. harmonics.l20[0] *= scaleFactor;
  81530. harmonics.l20[1] *= scaleFactor;
  81531. harmonics.l20[2] *= scaleFactor;
  81532. harmonics.l21[0] *= scaleFactor;
  81533. harmonics.l21[1] *= scaleFactor;
  81534. harmonics.l21[2] *= scaleFactor;
  81535. harmonics.l22[0] *= scaleFactor;
  81536. harmonics.l22[1] *= scaleFactor;
  81537. harmonics.l22[2] *= scaleFactor;
  81538. };
  81539. /**
  81540. * Convert spherical harmonics to spherical polynomial coefficients
  81541. * @param harmonics Spherical harmonic coefficients (9)
  81542. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81543. */
  81544. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81545. var rPi = 1 / Math.PI;
  81546. //x
  81547. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81548. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81549. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81550. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81551. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81552. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81553. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81554. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81555. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81556. //xx
  81557. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81558. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81559. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81560. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81561. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81562. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81563. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81564. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81565. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81566. //yz
  81567. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81568. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81569. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81570. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81571. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81572. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81573. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81574. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81575. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81576. };
  81577. /**
  81578. * Magic number identifying the env file.
  81579. */
  81580. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81581. return EnvironmentTextureTools;
  81582. }());
  81583. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81584. })(BABYLON || (BABYLON = {}));
  81585. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81586. var BABYLON;
  81587. (function (BABYLON) {
  81588. /**
  81589. * This represents a texture coming from an HDR input.
  81590. *
  81591. * The only supported format is currently panorama picture stored in RGBE format.
  81592. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81593. */
  81594. var HDRCubeTexture = /** @class */ (function (_super) {
  81595. __extends(HDRCubeTexture, _super);
  81596. /**
  81597. * Instantiates an HDRTexture from the following parameters.
  81598. *
  81599. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81600. * @param scene The scene the texture will be used in
  81601. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81602. * @param noMipmap Forces to not generate the mipmap if true
  81603. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81604. * @param gammaSpace 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)
  81605. * @param reserved Reserved flag for internal use.
  81606. */
  81607. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81608. if (noMipmap === void 0) { noMipmap = false; }
  81609. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81610. if (gammaSpace === void 0) { gammaSpace = false; }
  81611. if (reserved === void 0) { reserved = false; }
  81612. if (onLoad === void 0) { onLoad = null; }
  81613. if (onError === void 0) { onError = null; }
  81614. var _this = _super.call(this, scene) || this;
  81615. _this._generateHarmonics = true;
  81616. _this._onLoad = null;
  81617. _this._onError = null;
  81618. /**
  81619. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81620. */
  81621. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81622. _this._isBlocking = true;
  81623. _this._rotationY = 0;
  81624. /**
  81625. * Gets or sets the center of the bounding box associated with the cube texture
  81626. * It must define where the camera used to render the texture was set
  81627. */
  81628. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81629. if (!url) {
  81630. return _this;
  81631. }
  81632. _this.name = url;
  81633. _this.url = url;
  81634. _this.hasAlpha = false;
  81635. _this.isCube = true;
  81636. _this._textureMatrix = BABYLON.Matrix.Identity();
  81637. _this._onLoad = onLoad;
  81638. _this._onError = onError;
  81639. _this.gammaSpace = gammaSpace;
  81640. _this._noMipmap = noMipmap;
  81641. _this._size = size;
  81642. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81643. if (!_this._texture) {
  81644. if (!scene.useDelayedTextureLoading) {
  81645. _this.loadTexture();
  81646. }
  81647. else {
  81648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81649. }
  81650. }
  81651. return _this;
  81652. }
  81653. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81654. /**
  81655. * Gets wether or not the texture is blocking during loading.
  81656. */
  81657. get: function () {
  81658. return this._isBlocking;
  81659. },
  81660. /**
  81661. * Sets wether or not the texture is blocking during loading.
  81662. */
  81663. set: function (value) {
  81664. this._isBlocking = value;
  81665. },
  81666. enumerable: true,
  81667. configurable: true
  81668. });
  81669. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81670. /**
  81671. * Gets texture matrix rotation angle around Y axis radians.
  81672. */
  81673. get: function () {
  81674. return this._rotationY;
  81675. },
  81676. /**
  81677. * Sets texture matrix rotation angle around Y axis in radians.
  81678. */
  81679. set: function (value) {
  81680. this._rotationY = value;
  81681. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81682. },
  81683. enumerable: true,
  81684. configurable: true
  81685. });
  81686. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81687. get: function () {
  81688. return this._boundingBoxSize;
  81689. },
  81690. /**
  81691. * Gets or sets the size of the bounding box associated with the cube texture
  81692. * When defined, the cubemap will switch to local mode
  81693. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81694. * @example https://www.babylonjs-playground.com/#RNASML
  81695. */
  81696. set: function (value) {
  81697. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81698. return;
  81699. }
  81700. this._boundingBoxSize = value;
  81701. var scene = this.getScene();
  81702. if (scene) {
  81703. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81704. }
  81705. },
  81706. enumerable: true,
  81707. configurable: true
  81708. });
  81709. /**
  81710. * Occurs when the file is raw .hdr file.
  81711. */
  81712. HDRCubeTexture.prototype.loadTexture = function () {
  81713. var _this = this;
  81714. var callback = function (buffer) {
  81715. _this.lodGenerationOffset = 0.0;
  81716. _this.lodGenerationScale = 0.8;
  81717. var scene = _this.getScene();
  81718. if (!scene) {
  81719. return null;
  81720. }
  81721. // Extract the raw linear data.
  81722. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81723. // Generate harmonics if needed.
  81724. if (_this._generateHarmonics) {
  81725. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81726. _this.sphericalPolynomial = sphericalPolynomial;
  81727. }
  81728. var results = [];
  81729. var byteArray = null;
  81730. // Push each faces.
  81731. for (var j = 0; j < 6; j++) {
  81732. // Create uintarray fallback.
  81733. if (!scene.getEngine().getCaps().textureFloat) {
  81734. // 3 channels of 1 bytes per pixel in bytes.
  81735. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81736. byteArray = new Uint8Array(byteBuffer);
  81737. }
  81738. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81739. // If special cases.
  81740. if (_this.gammaSpace || byteArray) {
  81741. for (var i = 0; i < _this._size * _this._size; i++) {
  81742. // Put in gamma space if requested.
  81743. if (_this.gammaSpace) {
  81744. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81745. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81746. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81747. }
  81748. // Convert to int texture for fallback.
  81749. if (byteArray) {
  81750. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81751. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81752. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81753. // May use luminance instead if the result is not accurate.
  81754. var max = Math.max(Math.max(r, g), b);
  81755. if (max > 255) {
  81756. var scale = 255 / max;
  81757. r *= scale;
  81758. g *= scale;
  81759. b *= scale;
  81760. }
  81761. byteArray[(i * 3) + 0] = r;
  81762. byteArray[(i * 3) + 1] = g;
  81763. byteArray[(i * 3) + 2] = b;
  81764. }
  81765. }
  81766. }
  81767. if (byteArray) {
  81768. results.push(byteArray);
  81769. }
  81770. else {
  81771. results.push(dataFace);
  81772. }
  81773. }
  81774. return results;
  81775. };
  81776. var scene = this.getScene();
  81777. if (scene) {
  81778. 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, null, this._onLoad, this._onError);
  81779. }
  81780. };
  81781. HDRCubeTexture.prototype.clone = function () {
  81782. var scene = this.getScene();
  81783. if (!scene) {
  81784. return this;
  81785. }
  81786. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81787. // Base texture
  81788. newTexture.level = this.level;
  81789. newTexture.wrapU = this.wrapU;
  81790. newTexture.wrapV = this.wrapV;
  81791. newTexture.coordinatesIndex = this.coordinatesIndex;
  81792. newTexture.coordinatesMode = this.coordinatesMode;
  81793. return newTexture;
  81794. };
  81795. // Methods
  81796. HDRCubeTexture.prototype.delayLoad = function () {
  81797. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81798. return;
  81799. }
  81800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81801. this._texture = this._getFromCache(this.url, this._noMipmap);
  81802. if (!this._texture) {
  81803. this.loadTexture();
  81804. }
  81805. };
  81806. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81807. return this._textureMatrix;
  81808. };
  81809. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81810. this._textureMatrix = value;
  81811. };
  81812. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81813. var texture = null;
  81814. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81815. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81816. texture.name = parsedTexture.name;
  81817. texture.hasAlpha = parsedTexture.hasAlpha;
  81818. texture.level = parsedTexture.level;
  81819. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81820. texture.isBlocking = parsedTexture.isBlocking;
  81821. }
  81822. if (texture) {
  81823. if (parsedTexture.boundingBoxPosition) {
  81824. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81825. }
  81826. if (parsedTexture.boundingBoxSize) {
  81827. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81828. }
  81829. if (parsedTexture.rotationY) {
  81830. texture.rotationY = parsedTexture.rotationY;
  81831. }
  81832. }
  81833. return texture;
  81834. };
  81835. HDRCubeTexture.prototype.serialize = function () {
  81836. if (!this.name) {
  81837. return null;
  81838. }
  81839. var serializationObject = {};
  81840. serializationObject.name = this.name;
  81841. serializationObject.hasAlpha = this.hasAlpha;
  81842. serializationObject.isCube = true;
  81843. serializationObject.level = this.level;
  81844. serializationObject.size = this._size;
  81845. serializationObject.coordinatesMode = this.coordinatesMode;
  81846. serializationObject.useInGammaSpace = this.gammaSpace;
  81847. serializationObject.generateHarmonics = this._generateHarmonics;
  81848. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81849. serializationObject.noMipmap = this._noMipmap;
  81850. serializationObject.isBlocking = this._isBlocking;
  81851. serializationObject.rotationY = this._rotationY;
  81852. return serializationObject;
  81853. };
  81854. HDRCubeTexture._facesMapping = [
  81855. "right",
  81856. "left",
  81857. "up",
  81858. "down",
  81859. "front",
  81860. "back"
  81861. ];
  81862. return HDRCubeTexture;
  81863. }(BABYLON.BaseTexture));
  81864. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81865. })(BABYLON || (BABYLON = {}));
  81866. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81867. var BABYLON;
  81868. (function (BABYLON) {
  81869. var IndexedVector2 = /** @class */ (function (_super) {
  81870. __extends(IndexedVector2, _super);
  81871. function IndexedVector2(original, index) {
  81872. var _this = _super.call(this, original.x, original.y) || this;
  81873. _this.index = index;
  81874. return _this;
  81875. }
  81876. return IndexedVector2;
  81877. }(BABYLON.Vector2));
  81878. var PolygonPoints = /** @class */ (function () {
  81879. function PolygonPoints() {
  81880. this.elements = new Array();
  81881. }
  81882. PolygonPoints.prototype.add = function (originalPoints) {
  81883. var _this = this;
  81884. var result = new Array();
  81885. originalPoints.forEach(function (point) {
  81886. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81887. var newPoint = new IndexedVector2(point, _this.elements.length);
  81888. result.push(newPoint);
  81889. _this.elements.push(newPoint);
  81890. }
  81891. });
  81892. return result;
  81893. };
  81894. PolygonPoints.prototype.computeBounds = function () {
  81895. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81896. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81897. this.elements.forEach(function (point) {
  81898. // x
  81899. if (point.x < lmin.x) {
  81900. lmin.x = point.x;
  81901. }
  81902. else if (point.x > lmax.x) {
  81903. lmax.x = point.x;
  81904. }
  81905. // y
  81906. if (point.y < lmin.y) {
  81907. lmin.y = point.y;
  81908. }
  81909. else if (point.y > lmax.y) {
  81910. lmax.y = point.y;
  81911. }
  81912. });
  81913. return {
  81914. min: lmin,
  81915. max: lmax,
  81916. width: lmax.x - lmin.x,
  81917. height: lmax.y - lmin.y
  81918. };
  81919. };
  81920. return PolygonPoints;
  81921. }());
  81922. var Polygon = /** @class */ (function () {
  81923. function Polygon() {
  81924. }
  81925. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81926. return [
  81927. new BABYLON.Vector2(xmin, ymin),
  81928. new BABYLON.Vector2(xmax, ymin),
  81929. new BABYLON.Vector2(xmax, ymax),
  81930. new BABYLON.Vector2(xmin, ymax)
  81931. ];
  81932. };
  81933. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81934. if (cx === void 0) { cx = 0; }
  81935. if (cy === void 0) { cy = 0; }
  81936. if (numberOfSides === void 0) { numberOfSides = 32; }
  81937. var result = new Array();
  81938. var angle = 0;
  81939. var increment = (Math.PI * 2) / numberOfSides;
  81940. for (var i = 0; i < numberOfSides; i++) {
  81941. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81942. angle -= increment;
  81943. }
  81944. return result;
  81945. };
  81946. Polygon.Parse = function (input) {
  81947. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81948. var i, result = [];
  81949. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81950. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81951. }
  81952. return result;
  81953. };
  81954. Polygon.StartingAt = function (x, y) {
  81955. return BABYLON.Path2.StartingAt(x, y);
  81956. };
  81957. return Polygon;
  81958. }());
  81959. BABYLON.Polygon = Polygon;
  81960. var PolygonMeshBuilder = /** @class */ (function () {
  81961. function PolygonMeshBuilder(name, contours, scene) {
  81962. this._points = new PolygonPoints();
  81963. this._outlinepoints = new PolygonPoints();
  81964. this._holes = new Array();
  81965. this._epoints = new Array();
  81966. this._eholes = new Array();
  81967. this._name = name;
  81968. this._scene = scene;
  81969. var points;
  81970. if (contours instanceof BABYLON.Path2) {
  81971. points = contours.getPoints();
  81972. }
  81973. else {
  81974. points = contours;
  81975. }
  81976. this._addToepoint(points);
  81977. this._points.add(points);
  81978. this._outlinepoints.add(points);
  81979. if (typeof earcut === 'undefined') {
  81980. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81981. }
  81982. }
  81983. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81984. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81985. var p = points_1[_i];
  81986. this._epoints.push(p.x, p.y);
  81987. }
  81988. };
  81989. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81990. this._points.add(hole);
  81991. var holepoints = new PolygonPoints();
  81992. holepoints.add(hole);
  81993. this._holes.push(holepoints);
  81994. this._eholes.push(this._epoints.length / 2);
  81995. this._addToepoint(hole);
  81996. return this;
  81997. };
  81998. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81999. var _this = this;
  82000. if (updatable === void 0) { updatable = false; }
  82001. if (depth === void 0) { depth = 0; }
  82002. var result = new BABYLON.Mesh(this._name, this._scene);
  82003. var normals = new Array();
  82004. var positions = new Array();
  82005. var uvs = new Array();
  82006. var bounds = this._points.computeBounds();
  82007. this._points.elements.forEach(function (p) {
  82008. normals.push(0, 1.0, 0);
  82009. positions.push(p.x, 0, p.y);
  82010. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82011. });
  82012. var indices = new Array();
  82013. var res = earcut(this._epoints, this._eholes, 2);
  82014. for (var i = 0; i < res.length; i++) {
  82015. indices.push(res[i]);
  82016. }
  82017. if (depth > 0) {
  82018. var positionscount = (positions.length / 3); //get the current pointcount
  82019. this._points.elements.forEach(function (p) {
  82020. normals.push(0, -1.0, 0);
  82021. positions.push(p.x, -depth, p.y);
  82022. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82023. });
  82024. var totalCount = indices.length;
  82025. for (var i = 0; i < totalCount; i += 3) {
  82026. var i0 = indices[i + 0];
  82027. var i1 = indices[i + 1];
  82028. var i2 = indices[i + 2];
  82029. indices.push(i2 + positionscount);
  82030. indices.push(i1 + positionscount);
  82031. indices.push(i0 + positionscount);
  82032. }
  82033. //Add the sides
  82034. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82035. this._holes.forEach(function (hole) {
  82036. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82037. });
  82038. }
  82039. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82040. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82041. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82042. result.setIndices(indices);
  82043. return result;
  82044. };
  82045. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82046. var StartIndex = positions.length / 3;
  82047. var ulength = 0;
  82048. for (var i = 0; i < points.elements.length; i++) {
  82049. var p = points.elements[i];
  82050. var p1;
  82051. if ((i + 1) > points.elements.length - 1) {
  82052. p1 = points.elements[0];
  82053. }
  82054. else {
  82055. p1 = points.elements[i + 1];
  82056. }
  82057. positions.push(p.x, 0, p.y);
  82058. positions.push(p.x, -depth, p.y);
  82059. positions.push(p1.x, 0, p1.y);
  82060. positions.push(p1.x, -depth, p1.y);
  82061. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82062. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82063. var v3 = v2.subtract(v1);
  82064. var v4 = new BABYLON.Vector3(0, 1, 0);
  82065. var vn = BABYLON.Vector3.Cross(v3, v4);
  82066. vn = vn.normalize();
  82067. uvs.push(ulength / bounds.width, 0);
  82068. uvs.push(ulength / bounds.width, 1);
  82069. ulength += v3.length();
  82070. uvs.push((ulength / bounds.width), 0);
  82071. uvs.push((ulength / bounds.width), 1);
  82072. if (!flip) {
  82073. normals.push(-vn.x, -vn.y, -vn.z);
  82074. normals.push(-vn.x, -vn.y, -vn.z);
  82075. normals.push(-vn.x, -vn.y, -vn.z);
  82076. normals.push(-vn.x, -vn.y, -vn.z);
  82077. indices.push(StartIndex);
  82078. indices.push(StartIndex + 1);
  82079. indices.push(StartIndex + 2);
  82080. indices.push(StartIndex + 1);
  82081. indices.push(StartIndex + 3);
  82082. indices.push(StartIndex + 2);
  82083. }
  82084. else {
  82085. normals.push(vn.x, vn.y, vn.z);
  82086. normals.push(vn.x, vn.y, vn.z);
  82087. normals.push(vn.x, vn.y, vn.z);
  82088. normals.push(vn.x, vn.y, vn.z);
  82089. indices.push(StartIndex);
  82090. indices.push(StartIndex + 2);
  82091. indices.push(StartIndex + 1);
  82092. indices.push(StartIndex + 1);
  82093. indices.push(StartIndex + 2);
  82094. indices.push(StartIndex + 3);
  82095. }
  82096. StartIndex += 4;
  82097. }
  82098. ;
  82099. };
  82100. return PolygonMeshBuilder;
  82101. }());
  82102. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82103. })(BABYLON || (BABYLON = {}));
  82104. //# sourceMappingURL=babylon.polygonMesh.js.map
  82105. var BABYLON;
  82106. (function (BABYLON) {
  82107. // Unique ID when we import meshes from Babylon to CSG
  82108. var currentCSGMeshId = 0;
  82109. // # class Vertex
  82110. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82111. // one to provide additional features like texture coordinates and vertex
  82112. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82113. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82114. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82115. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82116. // is not used anywhere else.
  82117. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82118. var Vertex = /** @class */ (function () {
  82119. function Vertex(pos, normal, uv) {
  82120. this.pos = pos;
  82121. this.normal = normal;
  82122. this.uv = uv;
  82123. }
  82124. Vertex.prototype.clone = function () {
  82125. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82126. };
  82127. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82128. // orientation of a polygon is flipped.
  82129. Vertex.prototype.flip = function () {
  82130. this.normal = this.normal.scale(-1);
  82131. };
  82132. // Create a new vertex between this vertex and `other` by linearly
  82133. // interpolating all properties using a parameter of `t`. Subclasses should
  82134. // override this to interpolate additional properties.
  82135. Vertex.prototype.interpolate = function (other, t) {
  82136. 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));
  82137. };
  82138. return Vertex;
  82139. }());
  82140. // # class Plane
  82141. // Represents a plane in 3D space.
  82142. var Plane = /** @class */ (function () {
  82143. function Plane(normal, w) {
  82144. this.normal = normal;
  82145. this.w = w;
  82146. }
  82147. Plane.FromPoints = function (a, b, c) {
  82148. var v0 = c.subtract(a);
  82149. var v1 = b.subtract(a);
  82150. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82151. return null;
  82152. }
  82153. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82154. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82155. };
  82156. Plane.prototype.clone = function () {
  82157. return new Plane(this.normal.clone(), this.w);
  82158. };
  82159. Plane.prototype.flip = function () {
  82160. this.normal.scaleInPlace(-1);
  82161. this.w = -this.w;
  82162. };
  82163. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82164. // fragments in the appropriate lists. Coplanar polygons go into either
  82165. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82166. // respect to this plane. Polygons in front or in back of this plane go into
  82167. // either `front` or `back`.
  82168. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82169. var COPLANAR = 0;
  82170. var FRONT = 1;
  82171. var BACK = 2;
  82172. var SPANNING = 3;
  82173. // Classify each point as well as the entire polygon into one of the above
  82174. // four classes.
  82175. var polygonType = 0;
  82176. var types = [];
  82177. var i;
  82178. var t;
  82179. for (i = 0; i < polygon.vertices.length; i++) {
  82180. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82181. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82182. polygonType |= type;
  82183. types.push(type);
  82184. }
  82185. // Put the polygon in the correct list, splitting it when necessary.
  82186. switch (polygonType) {
  82187. case COPLANAR:
  82188. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82189. break;
  82190. case FRONT:
  82191. front.push(polygon);
  82192. break;
  82193. case BACK:
  82194. back.push(polygon);
  82195. break;
  82196. case SPANNING:
  82197. var f = [], b = [];
  82198. for (i = 0; i < polygon.vertices.length; i++) {
  82199. var j = (i + 1) % polygon.vertices.length;
  82200. var ti = types[i], tj = types[j];
  82201. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82202. if (ti !== BACK)
  82203. f.push(vi);
  82204. if (ti !== FRONT)
  82205. b.push(ti !== BACK ? vi.clone() : vi);
  82206. if ((ti | tj) === SPANNING) {
  82207. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82208. var v = vi.interpolate(vj, t);
  82209. f.push(v);
  82210. b.push(v.clone());
  82211. }
  82212. }
  82213. var poly;
  82214. if (f.length >= 3) {
  82215. poly = new Polygon(f, polygon.shared);
  82216. if (poly.plane)
  82217. front.push(poly);
  82218. }
  82219. if (b.length >= 3) {
  82220. poly = new Polygon(b, polygon.shared);
  82221. if (poly.plane)
  82222. back.push(poly);
  82223. }
  82224. break;
  82225. }
  82226. };
  82227. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82228. // point is on the plane.
  82229. Plane.EPSILON = 1e-5;
  82230. return Plane;
  82231. }());
  82232. // # class Polygon
  82233. // Represents a convex polygon. The vertices used to initialize a polygon must
  82234. // be coplanar and form a convex loop.
  82235. //
  82236. // Each convex polygon has a `shared` property, which is shared between all
  82237. // polygons that are clones of each other or were split from the same polygon.
  82238. // This can be used to define per-polygon properties (such as surface color).
  82239. var Polygon = /** @class */ (function () {
  82240. function Polygon(vertices, shared) {
  82241. this.vertices = vertices;
  82242. this.shared = shared;
  82243. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82244. }
  82245. Polygon.prototype.clone = function () {
  82246. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82247. return new Polygon(vertices, this.shared);
  82248. };
  82249. Polygon.prototype.flip = function () {
  82250. this.vertices.reverse().map(function (v) { v.flip(); });
  82251. this.plane.flip();
  82252. };
  82253. return Polygon;
  82254. }());
  82255. // # class Node
  82256. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82257. // by picking a polygon to split along. That polygon (and all other coplanar
  82258. // polygons) are added directly to that node and the other polygons are added to
  82259. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82260. // no distinction between internal and leaf nodes.
  82261. var Node = /** @class */ (function () {
  82262. function Node(polygons) {
  82263. this.plane = null;
  82264. this.front = null;
  82265. this.back = null;
  82266. this.polygons = new Array();
  82267. if (polygons) {
  82268. this.build(polygons);
  82269. }
  82270. }
  82271. Node.prototype.clone = function () {
  82272. var node = new Node();
  82273. node.plane = this.plane && this.plane.clone();
  82274. node.front = this.front && this.front.clone();
  82275. node.back = this.back && this.back.clone();
  82276. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82277. return node;
  82278. };
  82279. // Convert solid space to empty space and empty space to solid space.
  82280. Node.prototype.invert = function () {
  82281. for (var i = 0; i < this.polygons.length; i++) {
  82282. this.polygons[i].flip();
  82283. }
  82284. if (this.plane) {
  82285. this.plane.flip();
  82286. }
  82287. if (this.front) {
  82288. this.front.invert();
  82289. }
  82290. if (this.back) {
  82291. this.back.invert();
  82292. }
  82293. var temp = this.front;
  82294. this.front = this.back;
  82295. this.back = temp;
  82296. };
  82297. // Recursively remove all polygons in `polygons` that are inside this BSP
  82298. // tree.
  82299. Node.prototype.clipPolygons = function (polygons) {
  82300. if (!this.plane)
  82301. return polygons.slice();
  82302. var front = new Array(), back = new Array();
  82303. for (var i = 0; i < polygons.length; i++) {
  82304. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82305. }
  82306. if (this.front) {
  82307. front = this.front.clipPolygons(front);
  82308. }
  82309. if (this.back) {
  82310. back = this.back.clipPolygons(back);
  82311. }
  82312. else {
  82313. back = [];
  82314. }
  82315. return front.concat(back);
  82316. };
  82317. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82318. // `bsp`.
  82319. Node.prototype.clipTo = function (bsp) {
  82320. this.polygons = bsp.clipPolygons(this.polygons);
  82321. if (this.front)
  82322. this.front.clipTo(bsp);
  82323. if (this.back)
  82324. this.back.clipTo(bsp);
  82325. };
  82326. // Return a list of all polygons in this BSP tree.
  82327. Node.prototype.allPolygons = function () {
  82328. var polygons = this.polygons.slice();
  82329. if (this.front)
  82330. polygons = polygons.concat(this.front.allPolygons());
  82331. if (this.back)
  82332. polygons = polygons.concat(this.back.allPolygons());
  82333. return polygons;
  82334. };
  82335. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82336. // new polygons are filtered down to the bottom of the tree and become new
  82337. // nodes there. Each set of polygons is partitioned using the first polygon
  82338. // (no heuristic is used to pick a good split).
  82339. Node.prototype.build = function (polygons) {
  82340. if (!polygons.length)
  82341. return;
  82342. if (!this.plane)
  82343. this.plane = polygons[0].plane.clone();
  82344. var front = new Array(), back = new Array();
  82345. for (var i = 0; i < polygons.length; i++) {
  82346. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82347. }
  82348. if (front.length) {
  82349. if (!this.front)
  82350. this.front = new Node();
  82351. this.front.build(front);
  82352. }
  82353. if (back.length) {
  82354. if (!this.back)
  82355. this.back = new Node();
  82356. this.back.build(back);
  82357. }
  82358. };
  82359. return Node;
  82360. }());
  82361. var CSG = /** @class */ (function () {
  82362. function CSG() {
  82363. this.polygons = new Array();
  82364. }
  82365. // Convert BABYLON.Mesh to BABYLON.CSG
  82366. CSG.FromMesh = function (mesh) {
  82367. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82368. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82369. if (mesh instanceof BABYLON.Mesh) {
  82370. mesh.computeWorldMatrix(true);
  82371. matrix = mesh.getWorldMatrix();
  82372. meshPosition = mesh.position.clone();
  82373. meshRotation = mesh.rotation.clone();
  82374. if (mesh.rotationQuaternion) {
  82375. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82376. }
  82377. meshScaling = mesh.scaling.clone();
  82378. }
  82379. else {
  82380. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82381. }
  82382. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82383. var subMeshes = mesh.subMeshes;
  82384. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82385. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82386. vertices = [];
  82387. for (var j = 0; j < 3; j++) {
  82388. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82389. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82390. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82391. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82392. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82393. vertex = new Vertex(position, normal, uv);
  82394. vertices.push(vertex);
  82395. }
  82396. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82397. // To handle the case of degenerated triangle
  82398. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82399. if (polygon.plane)
  82400. polygons.push(polygon);
  82401. }
  82402. }
  82403. var csg = CSG.FromPolygons(polygons);
  82404. csg.matrix = matrix;
  82405. csg.position = meshPosition;
  82406. csg.rotation = meshRotation;
  82407. csg.scaling = meshScaling;
  82408. csg.rotationQuaternion = meshRotationQuaternion;
  82409. currentCSGMeshId++;
  82410. return csg;
  82411. };
  82412. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82413. CSG.FromPolygons = function (polygons) {
  82414. var csg = new CSG();
  82415. csg.polygons = polygons;
  82416. return csg;
  82417. };
  82418. CSG.prototype.clone = function () {
  82419. var csg = new CSG();
  82420. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82421. csg.copyTransformAttributes(this);
  82422. return csg;
  82423. };
  82424. CSG.prototype.union = function (csg) {
  82425. var a = new Node(this.clone().polygons);
  82426. var b = new Node(csg.clone().polygons);
  82427. a.clipTo(b);
  82428. b.clipTo(a);
  82429. b.invert();
  82430. b.clipTo(a);
  82431. b.invert();
  82432. a.build(b.allPolygons());
  82433. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82434. };
  82435. CSG.prototype.unionInPlace = function (csg) {
  82436. var a = new Node(this.polygons);
  82437. var b = new Node(csg.polygons);
  82438. a.clipTo(b);
  82439. b.clipTo(a);
  82440. b.invert();
  82441. b.clipTo(a);
  82442. b.invert();
  82443. a.build(b.allPolygons());
  82444. this.polygons = a.allPolygons();
  82445. };
  82446. CSG.prototype.subtract = function (csg) {
  82447. var a = new Node(this.clone().polygons);
  82448. var b = new Node(csg.clone().polygons);
  82449. a.invert();
  82450. a.clipTo(b);
  82451. b.clipTo(a);
  82452. b.invert();
  82453. b.clipTo(a);
  82454. b.invert();
  82455. a.build(b.allPolygons());
  82456. a.invert();
  82457. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82458. };
  82459. CSG.prototype.subtractInPlace = function (csg) {
  82460. var a = new Node(this.polygons);
  82461. var b = new Node(csg.polygons);
  82462. a.invert();
  82463. a.clipTo(b);
  82464. b.clipTo(a);
  82465. b.invert();
  82466. b.clipTo(a);
  82467. b.invert();
  82468. a.build(b.allPolygons());
  82469. a.invert();
  82470. this.polygons = a.allPolygons();
  82471. };
  82472. CSG.prototype.intersect = function (csg) {
  82473. var a = new Node(this.clone().polygons);
  82474. var b = new Node(csg.clone().polygons);
  82475. a.invert();
  82476. b.clipTo(a);
  82477. b.invert();
  82478. a.clipTo(b);
  82479. b.clipTo(a);
  82480. a.build(b.allPolygons());
  82481. a.invert();
  82482. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82483. };
  82484. CSG.prototype.intersectInPlace = function (csg) {
  82485. var a = new Node(this.polygons);
  82486. var b = new Node(csg.polygons);
  82487. a.invert();
  82488. b.clipTo(a);
  82489. b.invert();
  82490. a.clipTo(b);
  82491. b.clipTo(a);
  82492. a.build(b.allPolygons());
  82493. a.invert();
  82494. this.polygons = a.allPolygons();
  82495. };
  82496. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82497. // not modified.
  82498. CSG.prototype.inverse = function () {
  82499. var csg = this.clone();
  82500. csg.inverseInPlace();
  82501. return csg;
  82502. };
  82503. CSG.prototype.inverseInPlace = function () {
  82504. this.polygons.map(function (p) { p.flip(); });
  82505. };
  82506. // This is used to keep meshes transformations so they can be restored
  82507. // when we build back a Babylon Mesh
  82508. // NB : All CSG operations are performed in world coordinates
  82509. CSG.prototype.copyTransformAttributes = function (csg) {
  82510. this.matrix = csg.matrix;
  82511. this.position = csg.position;
  82512. this.rotation = csg.rotation;
  82513. this.scaling = csg.scaling;
  82514. this.rotationQuaternion = csg.rotationQuaternion;
  82515. return this;
  82516. };
  82517. // Build Raw mesh from CSG
  82518. // Coordinates here are in world space
  82519. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82520. var matrix = this.matrix.clone();
  82521. matrix.invert();
  82522. 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;
  82523. if (keepSubMeshes) {
  82524. // Sort Polygons, since subMeshes are indices range
  82525. polygons.sort(function (a, b) {
  82526. if (a.shared.meshId === b.shared.meshId) {
  82527. return a.shared.subMeshId - b.shared.subMeshId;
  82528. }
  82529. else {
  82530. return a.shared.meshId - b.shared.meshId;
  82531. }
  82532. });
  82533. }
  82534. for (var i = 0, il = polygons.length; i < il; i++) {
  82535. polygon = polygons[i];
  82536. // Building SubMeshes
  82537. if (!subMesh_dict[polygon.shared.meshId]) {
  82538. subMesh_dict[polygon.shared.meshId] = {};
  82539. }
  82540. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82541. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82542. indexStart: +Infinity,
  82543. indexEnd: -Infinity,
  82544. materialIndex: polygon.shared.materialIndex
  82545. };
  82546. }
  82547. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82548. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82549. polygonIndices[0] = 0;
  82550. polygonIndices[1] = j - 1;
  82551. polygonIndices[2] = j;
  82552. for (var k = 0; k < 3; k++) {
  82553. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82554. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82555. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82556. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82557. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82558. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82559. // Check if 2 points can be merged
  82560. if (!(typeof vertex_idx !== 'undefined' &&
  82561. normals[vertex_idx * 3] === localNormal.x &&
  82562. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82563. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82564. uvs[vertex_idx * 2] === uv.x &&
  82565. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82566. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82567. uvs.push(uv.x, uv.y);
  82568. normals.push(normal.x, normal.y, normal.z);
  82569. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82570. }
  82571. indices.push(vertex_idx);
  82572. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82573. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82574. currentIndex++;
  82575. }
  82576. }
  82577. }
  82578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82579. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82580. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82581. mesh.setIndices(indices, null);
  82582. if (keepSubMeshes) {
  82583. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82584. var materialIndexOffset = 0, materialMaxIndex;
  82585. mesh.subMeshes = new Array();
  82586. for (var m in subMesh_dict) {
  82587. materialMaxIndex = -1;
  82588. for (var sm in subMesh_dict[m]) {
  82589. subMesh_obj = subMesh_dict[m][sm];
  82590. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82591. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82592. }
  82593. materialIndexOffset += ++materialMaxIndex;
  82594. }
  82595. }
  82596. return mesh;
  82597. };
  82598. // Build Mesh from CSG taking material and transforms into account
  82599. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82600. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82601. mesh.material = material;
  82602. mesh.position.copyFrom(this.position);
  82603. mesh.rotation.copyFrom(this.rotation);
  82604. if (this.rotationQuaternion) {
  82605. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82606. }
  82607. mesh.scaling.copyFrom(this.scaling);
  82608. mesh.computeWorldMatrix(true);
  82609. return mesh;
  82610. };
  82611. return CSG;
  82612. }());
  82613. BABYLON.CSG = CSG;
  82614. })(BABYLON || (BABYLON = {}));
  82615. //# sourceMappingURL=babylon.csg.js.map
  82616. var BABYLON;
  82617. (function (BABYLON) {
  82618. var LensFlare = /** @class */ (function () {
  82619. function LensFlare(size, position, color, imgUrl, system) {
  82620. this.size = size;
  82621. this.position = position;
  82622. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82623. this.color = color || new BABYLON.Color3(1, 1, 1);
  82624. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82625. this._system = system;
  82626. system.lensFlares.push(this);
  82627. }
  82628. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82629. return new LensFlare(size, position, color, imgUrl, system);
  82630. };
  82631. LensFlare.prototype.dispose = function () {
  82632. if (this.texture) {
  82633. this.texture.dispose();
  82634. }
  82635. // Remove from scene
  82636. var index = this._system.lensFlares.indexOf(this);
  82637. this._system.lensFlares.splice(index, 1);
  82638. };
  82639. ;
  82640. return LensFlare;
  82641. }());
  82642. BABYLON.LensFlare = LensFlare;
  82643. })(BABYLON || (BABYLON = {}));
  82644. //# sourceMappingURL=babylon.lensFlare.js.map
  82645. var BABYLON;
  82646. (function (BABYLON) {
  82647. var LensFlareSystem = /** @class */ (function () {
  82648. function LensFlareSystem(name, emitter, scene) {
  82649. this.name = name;
  82650. this.lensFlares = new Array();
  82651. this.borderLimit = 300;
  82652. this.viewportBorder = 0;
  82653. this.layerMask = 0x0FFFFFFF;
  82654. this._vertexBuffers = {};
  82655. this._isEnabled = true;
  82656. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82657. this._emitter = emitter;
  82658. this.id = name;
  82659. scene.lensFlareSystems.push(this);
  82660. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82661. var engine = scene.getEngine();
  82662. // VBO
  82663. var vertices = [];
  82664. vertices.push(1, 1);
  82665. vertices.push(-1, 1);
  82666. vertices.push(-1, -1);
  82667. vertices.push(1, -1);
  82668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82669. // Indices
  82670. var indices = [];
  82671. indices.push(0);
  82672. indices.push(1);
  82673. indices.push(2);
  82674. indices.push(0);
  82675. indices.push(2);
  82676. indices.push(3);
  82677. this._indexBuffer = engine.createIndexBuffer(indices);
  82678. // Effects
  82679. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82680. }
  82681. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82682. get: function () {
  82683. return this._isEnabled;
  82684. },
  82685. set: function (value) {
  82686. this._isEnabled = value;
  82687. },
  82688. enumerable: true,
  82689. configurable: true
  82690. });
  82691. LensFlareSystem.prototype.getScene = function () {
  82692. return this._scene;
  82693. };
  82694. LensFlareSystem.prototype.getEmitter = function () {
  82695. return this._emitter;
  82696. };
  82697. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82698. this._emitter = newEmitter;
  82699. };
  82700. LensFlareSystem.prototype.getEmitterPosition = function () {
  82701. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82702. };
  82703. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82704. var position = this.getEmitterPosition();
  82705. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82706. this._positionX = position.x;
  82707. this._positionY = position.y;
  82708. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82709. if (this.viewportBorder > 0) {
  82710. globalViewport.x -= this.viewportBorder;
  82711. globalViewport.y -= this.viewportBorder;
  82712. globalViewport.width += this.viewportBorder * 2;
  82713. globalViewport.height += this.viewportBorder * 2;
  82714. position.x += this.viewportBorder;
  82715. position.y += this.viewportBorder;
  82716. this._positionX += this.viewportBorder;
  82717. this._positionY += this.viewportBorder;
  82718. }
  82719. if (position.z > 0) {
  82720. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82721. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82722. return true;
  82723. }
  82724. return true;
  82725. }
  82726. return false;
  82727. };
  82728. LensFlareSystem.prototype._isVisible = function () {
  82729. if (!this._isEnabled || !this._scene.activeCamera) {
  82730. return false;
  82731. }
  82732. var emitterPosition = this.getEmitterPosition();
  82733. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82734. var distance = direction.length();
  82735. direction.normalize();
  82736. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82737. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82738. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82739. };
  82740. LensFlareSystem.prototype.render = function () {
  82741. if (!this._effect.isReady() || !this._scene.activeCamera)
  82742. return false;
  82743. var engine = this._scene.getEngine();
  82744. var viewport = this._scene.activeCamera.viewport;
  82745. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82746. // Position
  82747. if (!this.computeEffectivePosition(globalViewport)) {
  82748. return false;
  82749. }
  82750. // Visibility
  82751. if (!this._isVisible()) {
  82752. return false;
  82753. }
  82754. // Intensity
  82755. var awayX;
  82756. var awayY;
  82757. if (this._positionX < this.borderLimit + globalViewport.x) {
  82758. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82759. }
  82760. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82761. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82762. }
  82763. else {
  82764. awayX = 0;
  82765. }
  82766. if (this._positionY < this.borderLimit + globalViewport.y) {
  82767. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82768. }
  82769. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82770. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82771. }
  82772. else {
  82773. awayY = 0;
  82774. }
  82775. var away = (awayX > awayY) ? awayX : awayY;
  82776. away -= this.viewportBorder;
  82777. if (away > this.borderLimit) {
  82778. away = this.borderLimit;
  82779. }
  82780. var intensity = 1.0 - (away / this.borderLimit);
  82781. if (intensity < 0) {
  82782. return false;
  82783. }
  82784. if (intensity > 1.0) {
  82785. intensity = 1.0;
  82786. }
  82787. if (this.viewportBorder > 0) {
  82788. globalViewport.x += this.viewportBorder;
  82789. globalViewport.y += this.viewportBorder;
  82790. globalViewport.width -= this.viewportBorder * 2;
  82791. globalViewport.height -= this.viewportBorder * 2;
  82792. this._positionX -= this.viewportBorder;
  82793. this._positionY -= this.viewportBorder;
  82794. }
  82795. // Position
  82796. var centerX = globalViewport.x + globalViewport.width / 2;
  82797. var centerY = globalViewport.y + globalViewport.height / 2;
  82798. var distX = centerX - this._positionX;
  82799. var distY = centerY - this._positionY;
  82800. // Effects
  82801. engine.enableEffect(this._effect);
  82802. engine.setState(false);
  82803. engine.setDepthBuffer(false);
  82804. // VBOs
  82805. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82806. // Flares
  82807. for (var index = 0; index < this.lensFlares.length; index++) {
  82808. var flare = this.lensFlares[index];
  82809. engine.setAlphaMode(flare.alphaMode);
  82810. var x = centerX - (distX * flare.position);
  82811. var y = centerY - (distY * flare.position);
  82812. var cw = flare.size;
  82813. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82814. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82815. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82816. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82817. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82818. // Texture
  82819. this._effect.setTexture("textureSampler", flare.texture);
  82820. // Color
  82821. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82822. // Draw order
  82823. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82824. }
  82825. engine.setDepthBuffer(true);
  82826. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82827. return true;
  82828. };
  82829. LensFlareSystem.prototype.dispose = function () {
  82830. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82831. if (vertexBuffer) {
  82832. vertexBuffer.dispose();
  82833. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82834. }
  82835. if (this._indexBuffer) {
  82836. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82837. this._indexBuffer = null;
  82838. }
  82839. while (this.lensFlares.length) {
  82840. this.lensFlares[0].dispose();
  82841. }
  82842. // Remove from scene
  82843. var index = this._scene.lensFlareSystems.indexOf(this);
  82844. this._scene.lensFlareSystems.splice(index, 1);
  82845. };
  82846. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82847. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82848. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82849. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82850. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82851. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82852. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82853. var parsedFlare = parsedLensFlareSystem.flares[index];
  82854. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82855. }
  82856. return lensFlareSystem;
  82857. };
  82858. LensFlareSystem.prototype.serialize = function () {
  82859. var serializationObject = {};
  82860. serializationObject.id = this.id;
  82861. serializationObject.name = this.name;
  82862. serializationObject.emitterId = this.getEmitter().id;
  82863. serializationObject.borderLimit = this.borderLimit;
  82864. serializationObject.flares = [];
  82865. for (var index = 0; index < this.lensFlares.length; index++) {
  82866. var flare = this.lensFlares[index];
  82867. serializationObject.flares.push({
  82868. size: flare.size,
  82869. position: flare.position,
  82870. color: flare.color.asArray(),
  82871. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82872. });
  82873. }
  82874. return serializationObject;
  82875. };
  82876. return LensFlareSystem;
  82877. }());
  82878. BABYLON.LensFlareSystem = LensFlareSystem;
  82879. })(BABYLON || (BABYLON = {}));
  82880. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82881. var BABYLON;
  82882. (function (BABYLON) {
  82883. /**
  82884. * This is a holder class for the physics joint created by the physics plugin.
  82885. * It holds a set of functions to control the underlying joint.
  82886. */
  82887. var PhysicsJoint = /** @class */ (function () {
  82888. function PhysicsJoint(type, jointData) {
  82889. this.type = type;
  82890. this.jointData = jointData;
  82891. jointData.nativeParams = jointData.nativeParams || {};
  82892. }
  82893. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82894. get: function () {
  82895. return this._physicsJoint;
  82896. },
  82897. set: function (newJoint) {
  82898. if (this._physicsJoint) {
  82899. //remove from the wolrd
  82900. }
  82901. this._physicsJoint = newJoint;
  82902. },
  82903. enumerable: true,
  82904. configurable: true
  82905. });
  82906. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82907. set: function (physicsPlugin) {
  82908. this._physicsPlugin = physicsPlugin;
  82909. },
  82910. enumerable: true,
  82911. configurable: true
  82912. });
  82913. /**
  82914. * Execute a function that is physics-plugin specific.
  82915. * @param {Function} func the function that will be executed.
  82916. * It accepts two parameters: the physics world and the physics joint.
  82917. */
  82918. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82919. func(this._physicsPlugin.world, this._physicsJoint);
  82920. };
  82921. //TODO check if the native joints are the same
  82922. //Joint Types
  82923. PhysicsJoint.DistanceJoint = 0;
  82924. PhysicsJoint.HingeJoint = 1;
  82925. PhysicsJoint.BallAndSocketJoint = 2;
  82926. PhysicsJoint.WheelJoint = 3;
  82927. PhysicsJoint.SliderJoint = 4;
  82928. //OIMO
  82929. PhysicsJoint.PrismaticJoint = 5;
  82930. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82931. PhysicsJoint.UniversalJoint = 6;
  82932. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82933. //Cannon
  82934. //Similar to a Ball-Joint. Different in params
  82935. PhysicsJoint.PointToPointJoint = 8;
  82936. //Cannon only at the moment
  82937. PhysicsJoint.SpringJoint = 9;
  82938. PhysicsJoint.LockJoint = 10;
  82939. return PhysicsJoint;
  82940. }());
  82941. BABYLON.PhysicsJoint = PhysicsJoint;
  82942. /**
  82943. * A class representing a physics distance joint.
  82944. */
  82945. var DistanceJoint = /** @class */ (function (_super) {
  82946. __extends(DistanceJoint, _super);
  82947. function DistanceJoint(jointData) {
  82948. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82949. }
  82950. /**
  82951. * Update the predefined distance.
  82952. */
  82953. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82954. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82955. };
  82956. return DistanceJoint;
  82957. }(PhysicsJoint));
  82958. BABYLON.DistanceJoint = DistanceJoint;
  82959. var MotorEnabledJoint = /** @class */ (function (_super) {
  82960. __extends(MotorEnabledJoint, _super);
  82961. function MotorEnabledJoint(type, jointData) {
  82962. return _super.call(this, type, jointData) || this;
  82963. }
  82964. /**
  82965. * Set the motor values.
  82966. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82967. * @param {number} force the force to apply
  82968. * @param {number} maxForce max force for this motor.
  82969. */
  82970. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82971. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82972. };
  82973. /**
  82974. * Set the motor's limits.
  82975. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82976. */
  82977. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82978. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82979. };
  82980. return MotorEnabledJoint;
  82981. }(PhysicsJoint));
  82982. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82983. /**
  82984. * This class represents a single hinge physics joint
  82985. */
  82986. var HingeJoint = /** @class */ (function (_super) {
  82987. __extends(HingeJoint, _super);
  82988. function HingeJoint(jointData) {
  82989. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82990. }
  82991. /**
  82992. * Set the motor values.
  82993. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82994. * @param {number} force the force to apply
  82995. * @param {number} maxForce max force for this motor.
  82996. */
  82997. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82998. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82999. };
  83000. /**
  83001. * Set the motor's limits.
  83002. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83003. */
  83004. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83005. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83006. };
  83007. return HingeJoint;
  83008. }(MotorEnabledJoint));
  83009. BABYLON.HingeJoint = HingeJoint;
  83010. /**
  83011. * This class represents a dual hinge physics joint (same as wheel joint)
  83012. */
  83013. var Hinge2Joint = /** @class */ (function (_super) {
  83014. __extends(Hinge2Joint, _super);
  83015. function Hinge2Joint(jointData) {
  83016. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83017. }
  83018. /**
  83019. * Set the motor values.
  83020. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83021. * @param {number} force the force to apply
  83022. * @param {number} maxForce max force for this motor.
  83023. * @param {motorIndex} the motor's index, 0 or 1.
  83024. */
  83025. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83026. if (motorIndex === void 0) { motorIndex = 0; }
  83027. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83028. };
  83029. /**
  83030. * Set the motor limits.
  83031. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83032. * @param {number} upperLimit the upper limit
  83033. * @param {number} lowerLimit lower limit
  83034. * @param {motorIndex} the motor's index, 0 or 1.
  83035. */
  83036. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83037. if (motorIndex === void 0) { motorIndex = 0; }
  83038. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83039. };
  83040. return Hinge2Joint;
  83041. }(MotorEnabledJoint));
  83042. BABYLON.Hinge2Joint = Hinge2Joint;
  83043. })(BABYLON || (BABYLON = {}));
  83044. //# sourceMappingURL=babylon.physicsJoint.js.map
  83045. var BABYLON;
  83046. (function (BABYLON) {
  83047. var PhysicsImpostor = /** @class */ (function () {
  83048. function PhysicsImpostor(object, type, _options, _scene) {
  83049. if (_options === void 0) { _options = { mass: 0 }; }
  83050. var _this = this;
  83051. this.object = object;
  83052. this.type = type;
  83053. this._options = _options;
  83054. this._scene = _scene;
  83055. this._bodyUpdateRequired = false;
  83056. this._onBeforePhysicsStepCallbacks = new Array();
  83057. this._onAfterPhysicsStepCallbacks = new Array();
  83058. this._onPhysicsCollideCallbacks = [];
  83059. this._deltaPosition = BABYLON.Vector3.Zero();
  83060. this._isDisposed = false;
  83061. //temp variables for parent rotation calculations
  83062. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83063. this._tmpQuat = new BABYLON.Quaternion();
  83064. this._tmpQuat2 = new BABYLON.Quaternion();
  83065. /**
  83066. * this function is executed by the physics engine.
  83067. */
  83068. this.beforeStep = function () {
  83069. if (!_this._physicsEngine) {
  83070. return;
  83071. }
  83072. _this.object.translate(_this._deltaPosition, -1);
  83073. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83074. _this.object.computeWorldMatrix(false);
  83075. if (_this.object.parent && _this.object.rotationQuaternion) {
  83076. _this.getParentsRotation();
  83077. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83078. }
  83079. else {
  83080. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83081. }
  83082. if (!_this._options.disableBidirectionalTransformation) {
  83083. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83084. }
  83085. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83086. func(_this);
  83087. });
  83088. };
  83089. /**
  83090. * this function is executed by the physics engine.
  83091. */
  83092. this.afterStep = function () {
  83093. if (!_this._physicsEngine) {
  83094. return;
  83095. }
  83096. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83097. func(_this);
  83098. });
  83099. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83100. // object has now its world rotation. needs to be converted to local.
  83101. if (_this.object.parent && _this.object.rotationQuaternion) {
  83102. _this.getParentsRotation();
  83103. _this._tmpQuat.conjugateInPlace();
  83104. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83105. }
  83106. // take the position set and make it the absolute position of this object.
  83107. _this.object.setAbsolutePosition(_this.object.position);
  83108. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83109. _this.object.translate(_this._deltaPosition, 1);
  83110. };
  83111. /**
  83112. * Legacy collision detection event support
  83113. */
  83114. this.onCollideEvent = null;
  83115. //event and body object due to cannon's event-based architecture.
  83116. this.onCollide = function (e) {
  83117. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83118. return;
  83119. }
  83120. if (!_this._physicsEngine) {
  83121. return;
  83122. }
  83123. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83124. if (otherImpostor) {
  83125. // Legacy collision detection event support
  83126. if (_this.onCollideEvent) {
  83127. _this.onCollideEvent(_this, otherImpostor);
  83128. }
  83129. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83130. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83131. }).forEach(function (obj) {
  83132. obj.callback(_this, otherImpostor);
  83133. });
  83134. }
  83135. };
  83136. //sanity check!
  83137. if (!this.object) {
  83138. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83139. return;
  83140. }
  83141. //legacy support for old syntax.
  83142. if (!this._scene && object.getScene) {
  83143. this._scene = object.getScene();
  83144. }
  83145. if (!this._scene) {
  83146. return;
  83147. }
  83148. this._physicsEngine = this._scene.getPhysicsEngine();
  83149. if (!this._physicsEngine) {
  83150. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83151. }
  83152. else {
  83153. //set the object's quaternion, if not set
  83154. if (!this.object.rotationQuaternion) {
  83155. if (this.object.rotation) {
  83156. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83157. }
  83158. else {
  83159. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83160. }
  83161. }
  83162. //default options params
  83163. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83164. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83165. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83166. this._joints = [];
  83167. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83168. if (!this.object.parent || this._options.ignoreParent) {
  83169. this._init();
  83170. }
  83171. else if (this.object.parent.physicsImpostor) {
  83172. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83173. }
  83174. }
  83175. }
  83176. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83177. get: function () {
  83178. return this._isDisposed;
  83179. },
  83180. enumerable: true,
  83181. configurable: true
  83182. });
  83183. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83184. get: function () {
  83185. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83186. },
  83187. set: function (value) {
  83188. this.setMass(value);
  83189. },
  83190. enumerable: true,
  83191. configurable: true
  83192. });
  83193. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83194. get: function () {
  83195. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83196. },
  83197. set: function (value) {
  83198. if (!this._physicsEngine) {
  83199. return;
  83200. }
  83201. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83202. },
  83203. enumerable: true,
  83204. configurable: true
  83205. });
  83206. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83207. get: function () {
  83208. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83209. },
  83210. set: function (value) {
  83211. if (!this._physicsEngine) {
  83212. return;
  83213. }
  83214. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83215. },
  83216. enumerable: true,
  83217. configurable: true
  83218. });
  83219. /**
  83220. * This function will completly initialize this impostor.
  83221. * It will create a new body - but only if this mesh has no parent.
  83222. * If it has, this impostor will not be used other than to define the impostor
  83223. * of the child mesh.
  83224. */
  83225. PhysicsImpostor.prototype._init = function () {
  83226. if (!this._physicsEngine) {
  83227. return;
  83228. }
  83229. this._physicsEngine.removeImpostor(this);
  83230. this.physicsBody = null;
  83231. this._parent = this._parent || this._getPhysicsParent();
  83232. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83233. this._physicsEngine.addImpostor(this);
  83234. }
  83235. };
  83236. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83237. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83238. var parentMesh = this.object.parent;
  83239. return parentMesh.physicsImpostor;
  83240. }
  83241. return null;
  83242. };
  83243. /**
  83244. * Should a new body be generated.
  83245. */
  83246. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83247. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83248. };
  83249. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83250. this.forceUpdate();
  83251. };
  83252. /**
  83253. * Force a regeneration of this or the parent's impostor's body.
  83254. * Use under cautious - This will remove all joints already implemented.
  83255. */
  83256. PhysicsImpostor.prototype.forceUpdate = function () {
  83257. this._init();
  83258. if (this.parent && !this._options.ignoreParent) {
  83259. this.parent.forceUpdate();
  83260. }
  83261. };
  83262. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83263. /*public get mesh(): AbstractMesh {
  83264. return this._mesh;
  83265. }*/
  83266. /**
  83267. * Gets the body that holds this impostor. Either its own, or its parent.
  83268. */
  83269. get: function () {
  83270. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83271. },
  83272. /**
  83273. * Set the physics body. Used mainly by the physics engine/plugin
  83274. */
  83275. set: function (physicsBody) {
  83276. if (this._physicsBody && this._physicsEngine) {
  83277. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83278. }
  83279. this._physicsBody = physicsBody;
  83280. this.resetUpdateFlags();
  83281. },
  83282. enumerable: true,
  83283. configurable: true
  83284. });
  83285. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83286. get: function () {
  83287. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83288. },
  83289. set: function (value) {
  83290. this._parent = value;
  83291. },
  83292. enumerable: true,
  83293. configurable: true
  83294. });
  83295. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83296. this._bodyUpdateRequired = false;
  83297. };
  83298. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83299. if (this.object.getBoundingInfo) {
  83300. var q = this.object.rotationQuaternion;
  83301. //reset rotation
  83302. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83303. //calculate the world matrix with no rotation
  83304. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83305. var boundingInfo = this.object.getBoundingInfo();
  83306. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83307. //bring back the rotation
  83308. this.object.rotationQuaternion = q;
  83309. //calculate the world matrix with the new rotation
  83310. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83311. return size;
  83312. }
  83313. else {
  83314. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83315. }
  83316. };
  83317. PhysicsImpostor.prototype.getObjectCenter = function () {
  83318. if (this.object.getBoundingInfo) {
  83319. var boundingInfo = this.object.getBoundingInfo();
  83320. return boundingInfo.boundingBox.centerWorld;
  83321. }
  83322. else {
  83323. return this.object.position;
  83324. }
  83325. };
  83326. /**
  83327. * Get a specific parametes from the options parameter.
  83328. */
  83329. PhysicsImpostor.prototype.getParam = function (paramName) {
  83330. return this._options[paramName];
  83331. };
  83332. /**
  83333. * Sets a specific parameter in the options given to the physics plugin
  83334. */
  83335. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83336. this._options[paramName] = value;
  83337. this._bodyUpdateRequired = true;
  83338. };
  83339. /**
  83340. * Specifically change the body's mass option. Won't recreate the physics body object
  83341. */
  83342. PhysicsImpostor.prototype.setMass = function (mass) {
  83343. if (this.getParam("mass") !== mass) {
  83344. this.setParam("mass", mass);
  83345. }
  83346. if (this._physicsEngine) {
  83347. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83348. }
  83349. };
  83350. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83351. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83352. };
  83353. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83354. if (this._physicsEngine) {
  83355. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83356. }
  83357. };
  83358. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83359. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83360. };
  83361. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83362. if (this._physicsEngine) {
  83363. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83364. }
  83365. };
  83366. /**
  83367. * Execute a function with the physics plugin native code.
  83368. * Provide a function the will have two variables - the world object and the physics body object.
  83369. */
  83370. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83371. if (this._physicsEngine) {
  83372. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83373. }
  83374. };
  83375. /**
  83376. * Register a function that will be executed before the physics world is stepping forward.
  83377. */
  83378. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83379. this._onBeforePhysicsStepCallbacks.push(func);
  83380. };
  83381. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83382. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83383. if (index > -1) {
  83384. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83385. }
  83386. else {
  83387. BABYLON.Tools.Warn("Function to remove was not found");
  83388. }
  83389. };
  83390. /**
  83391. * Register a function that will be executed after the physics step
  83392. */
  83393. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83394. this._onAfterPhysicsStepCallbacks.push(func);
  83395. };
  83396. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83397. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83398. if (index > -1) {
  83399. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83400. }
  83401. else {
  83402. BABYLON.Tools.Warn("Function to remove was not found");
  83403. }
  83404. };
  83405. /**
  83406. * register a function that will be executed when this impostor collides against a different body.
  83407. */
  83408. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83409. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83410. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83411. };
  83412. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83413. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83414. var index = -1;
  83415. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83416. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83417. // chcek the arrays match
  83418. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83419. return collidedAgainstList.indexOf(impostor) > -1;
  83420. });
  83421. if (sameList) {
  83422. index = idx;
  83423. }
  83424. return sameList;
  83425. }
  83426. return false;
  83427. });
  83428. if (found) {
  83429. this._onPhysicsCollideCallbacks.splice(index, 1);
  83430. }
  83431. else {
  83432. BABYLON.Tools.Warn("Function to remove was not found");
  83433. }
  83434. };
  83435. PhysicsImpostor.prototype.getParentsRotation = function () {
  83436. var parent = this.object.parent;
  83437. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83438. while (parent) {
  83439. if (parent.rotationQuaternion) {
  83440. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83441. }
  83442. else {
  83443. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83444. }
  83445. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83446. parent = parent.parent;
  83447. }
  83448. return this._tmpQuat;
  83449. };
  83450. /**
  83451. * Apply a force
  83452. */
  83453. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83454. if (this._physicsEngine) {
  83455. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83456. }
  83457. return this;
  83458. };
  83459. /**
  83460. * Apply an impulse
  83461. */
  83462. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83463. if (this._physicsEngine) {
  83464. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83465. }
  83466. return this;
  83467. };
  83468. /**
  83469. * A help function to create a joint.
  83470. */
  83471. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83472. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83473. this.addJoint(otherImpostor, joint);
  83474. return this;
  83475. };
  83476. /**
  83477. * Add a joint to this impostor with a different impostor.
  83478. */
  83479. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83480. this._joints.push({
  83481. otherImpostor: otherImpostor,
  83482. joint: joint
  83483. });
  83484. if (this._physicsEngine) {
  83485. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83486. }
  83487. return this;
  83488. };
  83489. /**
  83490. * Will keep this body still, in a sleep mode.
  83491. */
  83492. PhysicsImpostor.prototype.sleep = function () {
  83493. if (this._physicsEngine) {
  83494. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83495. }
  83496. return this;
  83497. };
  83498. /**
  83499. * Wake the body up.
  83500. */
  83501. PhysicsImpostor.prototype.wakeUp = function () {
  83502. if (this._physicsEngine) {
  83503. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83504. }
  83505. return this;
  83506. };
  83507. PhysicsImpostor.prototype.clone = function (newObject) {
  83508. if (!newObject)
  83509. return null;
  83510. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83511. };
  83512. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83513. var _this = this;
  83514. //no dispose if no physics engine is available.
  83515. if (!this._physicsEngine) {
  83516. return;
  83517. }
  83518. this._joints.forEach(function (j) {
  83519. if (_this._physicsEngine) {
  83520. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83521. }
  83522. });
  83523. //dispose the physics body
  83524. this._physicsEngine.removeImpostor(this);
  83525. if (this.parent) {
  83526. this.parent.forceUpdate();
  83527. }
  83528. else {
  83529. /*this._object.getChildMeshes().forEach(function(mesh) {
  83530. if (mesh.physicsImpostor) {
  83531. if (disposeChildren) {
  83532. mesh.physicsImpostor.dispose();
  83533. mesh.physicsImpostor = null;
  83534. }
  83535. }
  83536. })*/
  83537. }
  83538. this._isDisposed = true;
  83539. };
  83540. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83541. this._deltaPosition.copyFrom(position);
  83542. };
  83543. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83544. if (!this._deltaRotation) {
  83545. this._deltaRotation = new BABYLON.Quaternion();
  83546. }
  83547. this._deltaRotation.copyFrom(rotation);
  83548. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83549. };
  83550. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83551. if (this._physicsEngine) {
  83552. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83553. }
  83554. return this;
  83555. };
  83556. PhysicsImpostor.prototype.getRadius = function () {
  83557. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83558. };
  83559. /**
  83560. * Sync a bone with this impostor
  83561. * @param bone The bone to sync to the impostor.
  83562. * @param boneMesh The mesh that the bone is influencing.
  83563. * @param jointPivot The pivot of the joint / bone in local space.
  83564. * @param distToJoint Optional distance from the impostor to the joint.
  83565. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83566. */
  83567. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83568. var tempVec = PhysicsImpostor._tmpVecs[0];
  83569. var mesh = this.object;
  83570. if (mesh.rotationQuaternion) {
  83571. if (adjustRotation) {
  83572. var tempQuat = PhysicsImpostor._tmpQuat;
  83573. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83574. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83575. }
  83576. else {
  83577. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83578. }
  83579. }
  83580. tempVec.x = 0;
  83581. tempVec.y = 0;
  83582. tempVec.z = 0;
  83583. if (jointPivot) {
  83584. tempVec.x = jointPivot.x;
  83585. tempVec.y = jointPivot.y;
  83586. tempVec.z = jointPivot.z;
  83587. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83588. if (distToJoint === undefined || distToJoint === null) {
  83589. distToJoint = jointPivot.length();
  83590. }
  83591. tempVec.x *= distToJoint;
  83592. tempVec.y *= distToJoint;
  83593. tempVec.z *= distToJoint;
  83594. }
  83595. if (bone.getParent()) {
  83596. tempVec.addInPlace(mesh.getAbsolutePosition());
  83597. bone.setAbsolutePosition(tempVec, boneMesh);
  83598. }
  83599. else {
  83600. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83601. boneMesh.position.x -= tempVec.x;
  83602. boneMesh.position.y -= tempVec.y;
  83603. boneMesh.position.z -= tempVec.z;
  83604. }
  83605. };
  83606. /**
  83607. * Sync impostor to a bone
  83608. * @param bone The bone that the impostor will be synced to.
  83609. * @param boneMesh The mesh that the bone is influencing.
  83610. * @param jointPivot The pivot of the joint / bone in local space.
  83611. * @param distToJoint Optional distance from the impostor to the joint.
  83612. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83613. * @param boneAxis Optional vector3 axis the bone is aligned with
  83614. */
  83615. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83616. var mesh = this.object;
  83617. if (mesh.rotationQuaternion) {
  83618. if (adjustRotation) {
  83619. var tempQuat = PhysicsImpostor._tmpQuat;
  83620. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83621. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83622. }
  83623. else {
  83624. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83625. }
  83626. }
  83627. var pos = PhysicsImpostor._tmpVecs[0];
  83628. var boneDir = PhysicsImpostor._tmpVecs[1];
  83629. if (!boneAxis) {
  83630. boneAxis = PhysicsImpostor._tmpVecs[2];
  83631. boneAxis.x = 0;
  83632. boneAxis.y = 1;
  83633. boneAxis.z = 0;
  83634. }
  83635. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83636. bone.getAbsolutePositionToRef(boneMesh, pos);
  83637. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83638. distToJoint = jointPivot.length();
  83639. }
  83640. if (distToJoint !== undefined && distToJoint !== null) {
  83641. pos.x += boneDir.x * distToJoint;
  83642. pos.y += boneDir.y * distToJoint;
  83643. pos.z += boneDir.z * distToJoint;
  83644. }
  83645. mesh.setAbsolutePosition(pos);
  83646. };
  83647. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83648. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83649. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83650. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83651. //Impostor types
  83652. PhysicsImpostor.NoImpostor = 0;
  83653. PhysicsImpostor.SphereImpostor = 1;
  83654. PhysicsImpostor.BoxImpostor = 2;
  83655. PhysicsImpostor.PlaneImpostor = 3;
  83656. PhysicsImpostor.MeshImpostor = 4;
  83657. PhysicsImpostor.CylinderImpostor = 7;
  83658. PhysicsImpostor.ParticleImpostor = 8;
  83659. PhysicsImpostor.HeightmapImpostor = 9;
  83660. return PhysicsImpostor;
  83661. }());
  83662. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83663. })(BABYLON || (BABYLON = {}));
  83664. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83665. var BABYLON;
  83666. (function (BABYLON) {
  83667. var PhysicsEngine = /** @class */ (function () {
  83668. function PhysicsEngine(gravity, _physicsPlugin) {
  83669. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83670. this._physicsPlugin = _physicsPlugin;
  83671. //new methods and parameters
  83672. this._impostors = [];
  83673. this._joints = [];
  83674. if (!this._physicsPlugin.isSupported()) {
  83675. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83676. + "Please make sure it is included.");
  83677. }
  83678. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83679. this.setGravity(gravity);
  83680. this.setTimeStep();
  83681. }
  83682. PhysicsEngine.prototype.setGravity = function (gravity) {
  83683. this.gravity = gravity;
  83684. this._physicsPlugin.setGravity(this.gravity);
  83685. };
  83686. /**
  83687. * Set the time step of the physics engine.
  83688. * default is 1/60.
  83689. * To slow it down, enter 1/600 for example.
  83690. * To speed it up, 1/30
  83691. * @param {number} newTimeStep the new timestep to apply to this world.
  83692. */
  83693. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83694. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83695. this._physicsPlugin.setTimeStep(newTimeStep);
  83696. };
  83697. /**
  83698. * Get the time step of the physics engine.
  83699. */
  83700. PhysicsEngine.prototype.getTimeStep = function () {
  83701. return this._physicsPlugin.getTimeStep();
  83702. };
  83703. PhysicsEngine.prototype.dispose = function () {
  83704. this._impostors.forEach(function (impostor) {
  83705. impostor.dispose();
  83706. });
  83707. this._physicsPlugin.dispose();
  83708. };
  83709. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83710. return this._physicsPlugin.name;
  83711. };
  83712. /**
  83713. * Adding a new impostor for the impostor tracking.
  83714. * This will be done by the impostor itself.
  83715. * @param {PhysicsImpostor} impostor the impostor to add
  83716. */
  83717. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83718. impostor.uniqueId = this._impostors.push(impostor);
  83719. //if no parent, generate the body
  83720. if (!impostor.parent) {
  83721. this._physicsPlugin.generatePhysicsBody(impostor);
  83722. }
  83723. };
  83724. /**
  83725. * Remove an impostor from the engine.
  83726. * This impostor and its mesh will not longer be updated by the physics engine.
  83727. * @param {PhysicsImpostor} impostor the impostor to remove
  83728. */
  83729. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83730. var index = this._impostors.indexOf(impostor);
  83731. if (index > -1) {
  83732. var removed = this._impostors.splice(index, 1);
  83733. //Is it needed?
  83734. if (removed.length) {
  83735. //this will also remove it from the world.
  83736. removed[0].physicsBody = null;
  83737. }
  83738. }
  83739. };
  83740. /**
  83741. * Add a joint to the physics engine
  83742. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83743. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83744. * @param {PhysicsJoint} the joint that will connect both impostors.
  83745. */
  83746. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83747. var impostorJoint = {
  83748. mainImpostor: mainImpostor,
  83749. connectedImpostor: connectedImpostor,
  83750. joint: joint
  83751. };
  83752. joint.physicsPlugin = this._physicsPlugin;
  83753. this._joints.push(impostorJoint);
  83754. this._physicsPlugin.generateJoint(impostorJoint);
  83755. };
  83756. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83757. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83758. return (impostorJoint.connectedImpostor === connectedImpostor
  83759. && impostorJoint.joint === joint
  83760. && impostorJoint.mainImpostor === mainImpostor);
  83761. });
  83762. if (matchingJoints.length) {
  83763. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83764. //TODO remove it from the list as well
  83765. }
  83766. };
  83767. /**
  83768. * Called by the scene. no need to call it.
  83769. */
  83770. PhysicsEngine.prototype._step = function (delta) {
  83771. var _this = this;
  83772. //check if any mesh has no body / requires an update
  83773. this._impostors.forEach(function (impostor) {
  83774. if (impostor.isBodyInitRequired()) {
  83775. _this._physicsPlugin.generatePhysicsBody(impostor);
  83776. }
  83777. });
  83778. if (delta > 0.1) {
  83779. delta = 0.1;
  83780. }
  83781. else if (delta <= 0) {
  83782. delta = 1.0 / 60.0;
  83783. }
  83784. this._physicsPlugin.executeStep(delta, this._impostors);
  83785. };
  83786. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83787. return this._physicsPlugin;
  83788. };
  83789. PhysicsEngine.prototype.getImpostors = function () {
  83790. return this._impostors;
  83791. };
  83792. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83793. for (var i = 0; i < this._impostors.length; ++i) {
  83794. if (this._impostors[i].object === object) {
  83795. return this._impostors[i];
  83796. }
  83797. }
  83798. return null;
  83799. };
  83800. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83801. for (var i = 0; i < this._impostors.length; ++i) {
  83802. if (this._impostors[i].physicsBody === body) {
  83803. return this._impostors[i];
  83804. }
  83805. }
  83806. return null;
  83807. };
  83808. // Statics
  83809. PhysicsEngine.Epsilon = 0.001;
  83810. return PhysicsEngine;
  83811. }());
  83812. BABYLON.PhysicsEngine = PhysicsEngine;
  83813. })(BABYLON || (BABYLON = {}));
  83814. //# sourceMappingURL=babylon.physicsEngine.js.map
  83815. var BABYLON;
  83816. (function (BABYLON) {
  83817. var PhysicsHelper = /** @class */ (function () {
  83818. function PhysicsHelper(scene) {
  83819. this._scene = scene;
  83820. this._physicsEngine = this._scene.getPhysicsEngine();
  83821. if (!this._physicsEngine) {
  83822. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83823. }
  83824. }
  83825. /**
  83826. * @param {Vector3} origin the origin of the explosion
  83827. * @param {number} radius the explosion radius
  83828. * @param {number} strength the explosion strength
  83829. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83830. */
  83831. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83832. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83833. if (!this._physicsEngine) {
  83834. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83835. return null;
  83836. }
  83837. var impostors = this._physicsEngine.getImpostors();
  83838. if (impostors.length === 0) {
  83839. return null;
  83840. }
  83841. var event = new PhysicsRadialExplosionEvent(this._scene);
  83842. impostors.forEach(function (impostor) {
  83843. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83844. if (!impostorForceAndContactPoint) {
  83845. return;
  83846. }
  83847. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83848. });
  83849. event.dispose(false);
  83850. return event;
  83851. };
  83852. /**
  83853. * @param {Vector3} origin the origin of the explosion
  83854. * @param {number} radius the explosion radius
  83855. * @param {number} strength the explosion strength
  83856. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83857. */
  83858. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83859. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83860. if (!this._physicsEngine) {
  83861. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83862. return null;
  83863. }
  83864. var impostors = this._physicsEngine.getImpostors();
  83865. if (impostors.length === 0) {
  83866. return null;
  83867. }
  83868. var event = new PhysicsRadialExplosionEvent(this._scene);
  83869. impostors.forEach(function (impostor) {
  83870. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83871. if (!impostorForceAndContactPoint) {
  83872. return;
  83873. }
  83874. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83875. });
  83876. event.dispose(false);
  83877. return event;
  83878. };
  83879. /**
  83880. * @param {Vector3} origin the origin of the explosion
  83881. * @param {number} radius the explosion radius
  83882. * @param {number} strength the explosion strength
  83883. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83884. */
  83885. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83886. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83887. if (!this._physicsEngine) {
  83888. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83889. return null;
  83890. }
  83891. var impostors = this._physicsEngine.getImpostors();
  83892. if (impostors.length === 0) {
  83893. return null;
  83894. }
  83895. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83896. event.dispose(false);
  83897. return event;
  83898. };
  83899. /**
  83900. * @param {Vector3} origin the origin of the updraft
  83901. * @param {number} radius the radius of the updraft
  83902. * @param {number} strength the strength of the updraft
  83903. * @param {number} height the height of the updraft
  83904. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83905. */
  83906. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83907. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83908. if (!this._physicsEngine) {
  83909. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83910. return null;
  83911. }
  83912. if (this._physicsEngine.getImpostors().length === 0) {
  83913. return null;
  83914. }
  83915. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83916. event.dispose(false);
  83917. return event;
  83918. };
  83919. /**
  83920. * @param {Vector3} origin the of the vortex
  83921. * @param {number} radius the radius of the vortex
  83922. * @param {number} strength the strength of the vortex
  83923. * @param {number} height the height of the vortex
  83924. */
  83925. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83926. if (!this._physicsEngine) {
  83927. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83928. return null;
  83929. }
  83930. if (this._physicsEngine.getImpostors().length === 0) {
  83931. return null;
  83932. }
  83933. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83934. event.dispose(false);
  83935. return event;
  83936. };
  83937. return PhysicsHelper;
  83938. }());
  83939. BABYLON.PhysicsHelper = PhysicsHelper;
  83940. /***** Radial explosion *****/
  83941. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83942. function PhysicsRadialExplosionEvent(scene) {
  83943. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83944. this._rays = [];
  83945. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83946. this._scene = scene;
  83947. }
  83948. /**
  83949. * Returns the data related to the radial explosion event (sphere & rays).
  83950. * @returns {PhysicsRadialExplosionEventData}
  83951. */
  83952. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83953. this._dataFetched = true;
  83954. return {
  83955. sphere: this._sphere,
  83956. rays: this._rays,
  83957. };
  83958. };
  83959. /**
  83960. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83961. * @param impostor
  83962. * @param {Vector3} origin the origin of the explosion
  83963. * @param {number} radius the explosion radius
  83964. * @param {number} strength the explosion strength
  83965. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83966. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83967. */
  83968. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83969. if (impostor.mass === 0) {
  83970. return null;
  83971. }
  83972. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83973. return null;
  83974. }
  83975. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83976. return null;
  83977. }
  83978. var impostorObjectCenter = impostor.getObjectCenter();
  83979. var direction = impostorObjectCenter.subtract(origin);
  83980. var ray = new BABYLON.Ray(origin, direction, radius);
  83981. this._rays.push(ray);
  83982. var hit = ray.intersectsMesh(impostor.object);
  83983. var contactPoint = hit.pickedPoint;
  83984. if (!contactPoint) {
  83985. return null;
  83986. }
  83987. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83988. if (distanceFromOrigin > radius) {
  83989. return null;
  83990. }
  83991. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83992. ? strength
  83993. : strength * (1 - (distanceFromOrigin / radius));
  83994. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83995. return { force: force, contactPoint: contactPoint };
  83996. };
  83997. /**
  83998. * Disposes the sphere.
  83999. * @param {bolean} force
  84000. */
  84001. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84002. var _this = this;
  84003. if (force === void 0) { force = true; }
  84004. if (force) {
  84005. this._sphere.dispose();
  84006. }
  84007. else {
  84008. setTimeout(function () {
  84009. if (!_this._dataFetched) {
  84010. _this._sphere.dispose();
  84011. }
  84012. }, 0);
  84013. }
  84014. };
  84015. /*** Helpers ***/
  84016. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84017. if (!this._sphere) {
  84018. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84019. this._sphere.isVisible = false;
  84020. }
  84021. };
  84022. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84023. var impostorObject = impostor.object;
  84024. this._prepareSphere();
  84025. this._sphere.position = origin;
  84026. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84027. this._sphere._updateBoundingInfo();
  84028. this._sphere.computeWorldMatrix(true);
  84029. return this._sphere.intersectsMesh(impostorObject, true);
  84030. };
  84031. return PhysicsRadialExplosionEvent;
  84032. }());
  84033. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84034. /***** Gravitational Field *****/
  84035. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84036. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84037. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84038. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84039. this._physicsHelper = physicsHelper;
  84040. this._scene = scene;
  84041. this._origin = origin;
  84042. this._radius = radius;
  84043. this._strength = strength;
  84044. this._falloff = falloff;
  84045. this._tickCallback = this._tick.bind(this);
  84046. }
  84047. /**
  84048. * Returns the data related to the gravitational field event (sphere).
  84049. * @returns {PhysicsGravitationalFieldEventData}
  84050. */
  84051. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84052. this._dataFetched = true;
  84053. return {
  84054. sphere: this._sphere,
  84055. };
  84056. };
  84057. /**
  84058. * Enables the gravitational field.
  84059. */
  84060. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84061. this._tickCallback.call(this);
  84062. this._scene.registerBeforeRender(this._tickCallback);
  84063. };
  84064. /**
  84065. * Disables the gravitational field.
  84066. */
  84067. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84068. this._scene.unregisterBeforeRender(this._tickCallback);
  84069. };
  84070. /**
  84071. * Disposes the sphere.
  84072. * @param {bolean} force
  84073. */
  84074. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84075. var _this = this;
  84076. if (force === void 0) { force = true; }
  84077. if (force) {
  84078. this._sphere.dispose();
  84079. }
  84080. else {
  84081. setTimeout(function () {
  84082. if (!_this._dataFetched) {
  84083. _this._sphere.dispose();
  84084. }
  84085. }, 0);
  84086. }
  84087. };
  84088. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84089. // Since the params won't change, we fetch the event only once
  84090. if (this._sphere) {
  84091. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84092. }
  84093. else {
  84094. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84095. if (radialExplosionEvent) {
  84096. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84097. }
  84098. }
  84099. };
  84100. return PhysicsGravitationalFieldEvent;
  84101. }());
  84102. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84103. /***** Updraft *****/
  84104. var PhysicsUpdraftEvent = /** @class */ (function () {
  84105. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84106. this._scene = _scene;
  84107. this._origin = _origin;
  84108. this._radius = _radius;
  84109. this._strength = _strength;
  84110. this._height = _height;
  84111. this._updraftMode = _updraftMode;
  84112. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84113. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84114. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84115. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84116. this._physicsEngine = this._scene.getPhysicsEngine();
  84117. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84118. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84119. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84120. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84121. }
  84122. this._tickCallback = this._tick.bind(this);
  84123. }
  84124. /**
  84125. * Returns the data related to the updraft event (cylinder).
  84126. * @returns {PhysicsUpdraftEventData}
  84127. */
  84128. PhysicsUpdraftEvent.prototype.getData = function () {
  84129. this._dataFetched = true;
  84130. return {
  84131. cylinder: this._cylinder,
  84132. };
  84133. };
  84134. /**
  84135. * Enables the updraft.
  84136. */
  84137. PhysicsUpdraftEvent.prototype.enable = function () {
  84138. this._tickCallback.call(this);
  84139. this._scene.registerBeforeRender(this._tickCallback);
  84140. };
  84141. /**
  84142. * Disables the cortex.
  84143. */
  84144. PhysicsUpdraftEvent.prototype.disable = function () {
  84145. this._scene.unregisterBeforeRender(this._tickCallback);
  84146. };
  84147. /**
  84148. * Disposes the sphere.
  84149. * @param {bolean} force
  84150. */
  84151. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84152. var _this = this;
  84153. if (force === void 0) { force = true; }
  84154. if (force) {
  84155. this._cylinder.dispose();
  84156. }
  84157. else {
  84158. setTimeout(function () {
  84159. if (!_this._dataFetched) {
  84160. _this._cylinder.dispose();
  84161. }
  84162. }, 0);
  84163. }
  84164. };
  84165. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84166. if (impostor.mass === 0) {
  84167. return null;
  84168. }
  84169. if (!this._intersectsWithCylinder(impostor)) {
  84170. return null;
  84171. }
  84172. var impostorObjectCenter = impostor.getObjectCenter();
  84173. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84174. var direction = this._originDirection;
  84175. }
  84176. else {
  84177. var direction = impostorObjectCenter.subtract(this._originTop);
  84178. }
  84179. var multiplier = this._strength * -1;
  84180. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84181. return { force: force, contactPoint: impostorObjectCenter };
  84182. };
  84183. PhysicsUpdraftEvent.prototype._tick = function () {
  84184. var _this = this;
  84185. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84186. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84187. if (!impostorForceAndContactPoint) {
  84188. return;
  84189. }
  84190. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84191. });
  84192. };
  84193. /*** Helpers ***/
  84194. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84195. if (!this._cylinder) {
  84196. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84197. height: this._height,
  84198. diameter: this._radius * 2,
  84199. }, this._scene);
  84200. this._cylinder.isVisible = false;
  84201. }
  84202. };
  84203. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84204. var impostorObject = impostor.object;
  84205. this._prepareCylinder();
  84206. this._cylinder.position = this._cylinderPosition;
  84207. return this._cylinder.intersectsMesh(impostorObject, true);
  84208. };
  84209. return PhysicsUpdraftEvent;
  84210. }());
  84211. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84212. /***** Vortex *****/
  84213. var PhysicsVortexEvent = /** @class */ (function () {
  84214. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84215. this._scene = _scene;
  84216. this._origin = _origin;
  84217. this._radius = _radius;
  84218. this._strength = _strength;
  84219. this._height = _height;
  84220. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84221. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84222. this._updraftMultiplier = 0.02;
  84223. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84224. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84225. this._physicsEngine = this._scene.getPhysicsEngine();
  84226. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84227. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84228. this._tickCallback = this._tick.bind(this);
  84229. }
  84230. /**
  84231. * Returns the data related to the vortex event (cylinder).
  84232. * @returns {PhysicsVortexEventData}
  84233. */
  84234. PhysicsVortexEvent.prototype.getData = function () {
  84235. this._dataFetched = true;
  84236. return {
  84237. cylinder: this._cylinder,
  84238. };
  84239. };
  84240. /**
  84241. * Enables the vortex.
  84242. */
  84243. PhysicsVortexEvent.prototype.enable = function () {
  84244. this._tickCallback.call(this);
  84245. this._scene.registerBeforeRender(this._tickCallback);
  84246. };
  84247. /**
  84248. * Disables the cortex.
  84249. */
  84250. PhysicsVortexEvent.prototype.disable = function () {
  84251. this._scene.unregisterBeforeRender(this._tickCallback);
  84252. };
  84253. /**
  84254. * Disposes the sphere.
  84255. * @param {bolean} force
  84256. */
  84257. PhysicsVortexEvent.prototype.dispose = function (force) {
  84258. var _this = this;
  84259. if (force === void 0) { force = true; }
  84260. if (force) {
  84261. this._cylinder.dispose();
  84262. }
  84263. else {
  84264. setTimeout(function () {
  84265. if (!_this._dataFetched) {
  84266. _this._cylinder.dispose();
  84267. }
  84268. }, 0);
  84269. }
  84270. };
  84271. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84272. if (impostor.mass === 0) {
  84273. return null;
  84274. }
  84275. if (!this._intersectsWithCylinder(impostor)) {
  84276. return null;
  84277. }
  84278. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84279. return null;
  84280. }
  84281. var impostorObjectCenter = impostor.getObjectCenter();
  84282. 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)
  84283. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84284. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84285. var hit = ray.intersectsMesh(impostor.object);
  84286. var contactPoint = hit.pickedPoint;
  84287. if (!contactPoint) {
  84288. return null;
  84289. }
  84290. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84291. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84292. var directionToOrigin = contactPoint.normalize();
  84293. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84294. directionToOrigin = directionToOrigin.negate();
  84295. }
  84296. // TODO: find a more physically based solution
  84297. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84298. var forceX = directionToOrigin.x * this._strength / 8;
  84299. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84300. var forceZ = directionToOrigin.z * this._strength / 8;
  84301. }
  84302. else {
  84303. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84304. var forceY = this._originTop.y * this._updraftMultiplier;
  84305. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84306. }
  84307. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84308. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84309. return { force: force, contactPoint: impostorObjectCenter };
  84310. };
  84311. PhysicsVortexEvent.prototype._tick = function () {
  84312. var _this = this;
  84313. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84314. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84315. if (!impostorForceAndContactPoint) {
  84316. return;
  84317. }
  84318. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84319. });
  84320. };
  84321. /*** Helpers ***/
  84322. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84323. if (!this._cylinder) {
  84324. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84325. height: this._height,
  84326. diameter: this._radius * 2,
  84327. }, this._scene);
  84328. this._cylinder.isVisible = false;
  84329. }
  84330. };
  84331. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84332. var impostorObject = impostor.object;
  84333. this._prepareCylinder();
  84334. this._cylinder.position = this._cylinderPosition;
  84335. return this._cylinder.intersectsMesh(impostorObject, true);
  84336. };
  84337. return PhysicsVortexEvent;
  84338. }());
  84339. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84340. /***** Enums *****/
  84341. /**
  84342. * The strenght of the force in correspondence to the distance of the affected object
  84343. */
  84344. var PhysicsRadialImpulseFalloff;
  84345. (function (PhysicsRadialImpulseFalloff) {
  84346. /** Defines that impulse is constant in strength across it's whole radius */
  84347. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84348. /** DEfines that impulse gets weaker if it's further from the origin */
  84349. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84350. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84351. /**
  84352. * The strenght of the force in correspondence to the distance of the affected object
  84353. */
  84354. var PhysicsUpdraftMode;
  84355. (function (PhysicsUpdraftMode) {
  84356. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84357. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84358. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84359. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84360. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84361. })(BABYLON || (BABYLON = {}));
  84362. //# sourceMappingURL=babylon.physicsHelper.js.map
  84363. var BABYLON;
  84364. (function (BABYLON) {
  84365. var CannonJSPlugin = /** @class */ (function () {
  84366. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84367. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84368. if (iterations === void 0) { iterations = 10; }
  84369. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84370. this.name = "CannonJSPlugin";
  84371. this._physicsMaterials = new Array();
  84372. this._fixedTimeStep = 1 / 60;
  84373. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84374. this.BJSCANNON = CANNON;
  84375. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84376. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84377. this._tmpPosition = BABYLON.Vector3.Zero();
  84378. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84379. this._tmpUnityRotation = new BABYLON.Quaternion();
  84380. if (!this.isSupported()) {
  84381. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84382. return;
  84383. }
  84384. this._extendNamespace();
  84385. this.world = new this.BJSCANNON.World();
  84386. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84387. this.world.solver.iterations = iterations;
  84388. }
  84389. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84390. this.world.gravity.copy(gravity);
  84391. };
  84392. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84393. this._fixedTimeStep = timeStep;
  84394. };
  84395. CannonJSPlugin.prototype.getTimeStep = function () {
  84396. return this._fixedTimeStep;
  84397. };
  84398. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84399. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84400. };
  84401. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84402. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84403. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84404. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84405. };
  84406. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84407. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84408. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84409. impostor.physicsBody.applyForce(impulse, worldPoint);
  84410. };
  84411. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84412. //parent-child relationship. Does this impostor has a parent impostor?
  84413. if (impostor.parent) {
  84414. if (impostor.physicsBody) {
  84415. this.removePhysicsBody(impostor);
  84416. //TODO is that needed?
  84417. impostor.forceUpdate();
  84418. }
  84419. return;
  84420. }
  84421. //should a new body be created for this impostor?
  84422. if (impostor.isBodyInitRequired()) {
  84423. var shape = this._createShape(impostor);
  84424. //unregister events, if body is being changed
  84425. var oldBody = impostor.physicsBody;
  84426. if (oldBody) {
  84427. this.removePhysicsBody(impostor);
  84428. }
  84429. //create the body and material
  84430. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84431. var bodyCreationObject = {
  84432. mass: impostor.getParam("mass"),
  84433. material: material
  84434. };
  84435. // A simple extend, in case native options were used.
  84436. var nativeOptions = impostor.getParam("nativeOptions");
  84437. for (var key in nativeOptions) {
  84438. if (nativeOptions.hasOwnProperty(key)) {
  84439. bodyCreationObject[key] = nativeOptions[key];
  84440. }
  84441. }
  84442. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84443. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84444. this.world.addEventListener("preStep", impostor.beforeStep);
  84445. this.world.addEventListener("postStep", impostor.afterStep);
  84446. impostor.physicsBody.addShape(shape);
  84447. this.world.add(impostor.physicsBody);
  84448. //try to keep the body moving in the right direction by taking old properties.
  84449. //Should be tested!
  84450. if (oldBody) {
  84451. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84452. impostor.physicsBody[param].copy(oldBody[param]);
  84453. });
  84454. }
  84455. this._processChildMeshes(impostor);
  84456. }
  84457. //now update the body's transformation
  84458. this._updatePhysicsBodyTransformation(impostor);
  84459. };
  84460. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84461. var _this = this;
  84462. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84463. var currentRotation = mainImpostor.object.rotationQuaternion;
  84464. if (meshChildren.length) {
  84465. var processMesh = function (localPosition, mesh) {
  84466. if (!currentRotation || !mesh.rotationQuaternion) {
  84467. return;
  84468. }
  84469. var childImpostor = mesh.getPhysicsImpostor();
  84470. if (childImpostor) {
  84471. var parent = childImpostor.parent;
  84472. if (parent !== mainImpostor) {
  84473. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84474. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84475. if (childImpostor.physicsBody) {
  84476. _this.removePhysicsBody(childImpostor);
  84477. childImpostor.physicsBody = null;
  84478. }
  84479. childImpostor.parent = mainImpostor;
  84480. childImpostor.resetUpdateFlags();
  84481. 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));
  84482. //Add the mass of the children.
  84483. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84484. }
  84485. }
  84486. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84487. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84488. };
  84489. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84490. }
  84491. };
  84492. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84493. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84494. this.world.removeEventListener("preStep", impostor.beforeStep);
  84495. this.world.removeEventListener("postStep", impostor.afterStep);
  84496. this.world.remove(impostor.physicsBody);
  84497. };
  84498. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84499. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84500. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84501. if (!mainBody || !connectedBody) {
  84502. return;
  84503. }
  84504. var constraint;
  84505. var jointData = impostorJoint.joint.jointData;
  84506. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84507. var constraintData = {
  84508. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84509. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84510. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84511. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84512. maxForce: jointData.nativeParams.maxForce,
  84513. collideConnected: !!jointData.collision
  84514. };
  84515. switch (impostorJoint.joint.type) {
  84516. case BABYLON.PhysicsJoint.HingeJoint:
  84517. case BABYLON.PhysicsJoint.Hinge2Joint:
  84518. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84519. break;
  84520. case BABYLON.PhysicsJoint.DistanceJoint:
  84521. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84522. break;
  84523. case BABYLON.PhysicsJoint.SpringJoint:
  84524. var springData = jointData;
  84525. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84526. restLength: springData.length,
  84527. stiffness: springData.stiffness,
  84528. damping: springData.damping,
  84529. localAnchorA: constraintData.pivotA,
  84530. localAnchorB: constraintData.pivotB
  84531. });
  84532. break;
  84533. case BABYLON.PhysicsJoint.LockJoint:
  84534. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84535. break;
  84536. case BABYLON.PhysicsJoint.PointToPointJoint:
  84537. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84538. default:
  84539. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84540. break;
  84541. }
  84542. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84543. constraint.collideConnected = !!jointData.collision;
  84544. impostorJoint.joint.physicsJoint = constraint;
  84545. //don't add spring as constraint, as it is not one.
  84546. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84547. this.world.addConstraint(constraint);
  84548. }
  84549. else {
  84550. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84551. constraint.applyForce();
  84552. });
  84553. }
  84554. };
  84555. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84556. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84557. };
  84558. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84559. var index;
  84560. var mat;
  84561. for (index = 0; index < this._physicsMaterials.length; index++) {
  84562. mat = this._physicsMaterials[index];
  84563. if (mat.friction === friction && mat.restitution === restitution) {
  84564. return mat;
  84565. }
  84566. }
  84567. var currentMat = new this.BJSCANNON.Material(name);
  84568. currentMat.friction = friction;
  84569. currentMat.restitution = restitution;
  84570. this._physicsMaterials.push(currentMat);
  84571. return currentMat;
  84572. };
  84573. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84574. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84575. };
  84576. CannonJSPlugin.prototype._createShape = function (impostor) {
  84577. var object = impostor.object;
  84578. var returnValue;
  84579. var extendSize = impostor.getObjectExtendSize();
  84580. switch (impostor.type) {
  84581. case BABYLON.PhysicsImpostor.SphereImpostor:
  84582. var radiusX = extendSize.x;
  84583. var radiusY = extendSize.y;
  84584. var radiusZ = extendSize.z;
  84585. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84586. break;
  84587. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84588. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84589. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84590. break;
  84591. case BABYLON.PhysicsImpostor.BoxImpostor:
  84592. var box = extendSize.scale(0.5);
  84593. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84594. break;
  84595. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84596. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84597. returnValue = new this.BJSCANNON.Plane();
  84598. break;
  84599. case BABYLON.PhysicsImpostor.MeshImpostor:
  84600. // should transform the vertex data to world coordinates!!
  84601. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84602. var rawFaces = object.getIndices ? object.getIndices() : [];
  84603. if (!rawVerts)
  84604. return;
  84605. // get only scale! so the object could transform correctly.
  84606. var oldPosition = object.position.clone();
  84607. var oldRotation = object.rotation && object.rotation.clone();
  84608. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84609. object.position.copyFromFloats(0, 0, 0);
  84610. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84611. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84612. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84613. var transform = object.computeWorldMatrix(true);
  84614. // convert rawVerts to object space
  84615. var temp = new Array();
  84616. var index;
  84617. for (index = 0; index < rawVerts.length; index += 3) {
  84618. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84619. }
  84620. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84621. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84622. //now set back the transformation!
  84623. object.position.copyFrom(oldPosition);
  84624. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84625. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84626. break;
  84627. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84628. var oldPosition2 = object.position.clone();
  84629. var oldRotation2 = object.rotation && object.rotation.clone();
  84630. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84631. object.position.copyFromFloats(0, 0, 0);
  84632. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84633. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84634. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84635. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84636. returnValue = this._createHeightmap(object);
  84637. object.position.copyFrom(oldPosition2);
  84638. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84639. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84640. object.computeWorldMatrix(true);
  84641. break;
  84642. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84643. returnValue = new this.BJSCANNON.Particle();
  84644. break;
  84645. }
  84646. return returnValue;
  84647. };
  84648. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84649. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84650. var transform = object.computeWorldMatrix(true);
  84651. // convert rawVerts to object space
  84652. var temp = new Array();
  84653. var index;
  84654. for (index = 0; index < pos.length; index += 3) {
  84655. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84656. }
  84657. pos = temp;
  84658. var matrix = new Array();
  84659. //For now pointDepth will not be used and will be automatically calculated.
  84660. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84661. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84662. var boundingInfo = object.getBoundingInfo();
  84663. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84664. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84665. var elementSize = dim * 2 / arraySize;
  84666. for (var i = 0; i < pos.length; i = i + 3) {
  84667. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84668. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84669. var y = -pos[i + 2] + minY;
  84670. if (!matrix[x]) {
  84671. matrix[x] = [];
  84672. }
  84673. if (!matrix[x][z]) {
  84674. matrix[x][z] = y;
  84675. }
  84676. matrix[x][z] = Math.max(y, matrix[x][z]);
  84677. }
  84678. for (var x = 0; x <= arraySize; ++x) {
  84679. if (!matrix[x]) {
  84680. var loc = 1;
  84681. while (!matrix[(x + loc) % arraySize]) {
  84682. loc++;
  84683. }
  84684. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84685. //console.log("missing x", x);
  84686. }
  84687. for (var z = 0; z <= arraySize; ++z) {
  84688. if (!matrix[x][z]) {
  84689. var loc = 1;
  84690. var newValue;
  84691. while (newValue === undefined) {
  84692. newValue = matrix[x][(z + loc++) % arraySize];
  84693. }
  84694. matrix[x][z] = newValue;
  84695. }
  84696. }
  84697. }
  84698. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84699. elementSize: elementSize
  84700. });
  84701. //For future reference, needed for body transformation
  84702. shape.minY = minY;
  84703. return shape;
  84704. };
  84705. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84706. var object = impostor.object;
  84707. //make sure it is updated...
  84708. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84709. // The delta between the mesh position and the mesh bounding box center
  84710. var bInfo = object.getBoundingInfo();
  84711. if (!bInfo)
  84712. return;
  84713. var center = impostor.getObjectCenter();
  84714. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84715. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84716. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84717. this._tmpPosition.copyFrom(center);
  84718. var quaternion = object.rotationQuaternion;
  84719. if (!quaternion) {
  84720. return;
  84721. }
  84722. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84723. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84724. //-90 DEG in X, precalculated
  84725. quaternion = quaternion.multiply(this._minus90X);
  84726. //Invert! (Precalculated, 90 deg in X)
  84727. //No need to clone. this will never change.
  84728. impostor.setDeltaRotation(this._plus90X);
  84729. }
  84730. //If it is a heightfield, if should be centered.
  84731. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84732. var mesh = object;
  84733. var boundingInfo = mesh.getBoundingInfo();
  84734. //calculate the correct body position:
  84735. var rotationQuaternion = mesh.rotationQuaternion;
  84736. mesh.rotationQuaternion = this._tmpUnityRotation;
  84737. mesh.computeWorldMatrix(true);
  84738. //get original center with no rotation
  84739. var c = center.clone();
  84740. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84741. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84742. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84743. mesh.setPreTransformMatrix(p);
  84744. mesh.computeWorldMatrix(true);
  84745. //calculate the translation
  84746. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84747. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84748. //add it inverted to the delta
  84749. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84750. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84751. //rotation is back
  84752. mesh.rotationQuaternion = rotationQuaternion;
  84753. mesh.setPreTransformMatrix(oldPivot);
  84754. mesh.computeWorldMatrix(true);
  84755. }
  84756. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84757. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84758. //this._tmpPosition.copyFrom(object.position);
  84759. }
  84760. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84761. //Now update the impostor object
  84762. impostor.physicsBody.position.copy(this._tmpPosition);
  84763. impostor.physicsBody.quaternion.copy(quaternion);
  84764. };
  84765. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84766. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84767. if (impostor.object.rotationQuaternion) {
  84768. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84769. }
  84770. };
  84771. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84772. impostor.physicsBody.position.copy(newPosition);
  84773. impostor.physicsBody.quaternion.copy(newRotation);
  84774. };
  84775. CannonJSPlugin.prototype.isSupported = function () {
  84776. return this.BJSCANNON !== undefined;
  84777. };
  84778. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84779. impostor.physicsBody.velocity.copy(velocity);
  84780. };
  84781. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84782. impostor.physicsBody.angularVelocity.copy(velocity);
  84783. };
  84784. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84785. var v = impostor.physicsBody.velocity;
  84786. if (!v) {
  84787. return null;
  84788. }
  84789. return new BABYLON.Vector3(v.x, v.y, v.z);
  84790. };
  84791. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84792. var v = impostor.physicsBody.angularVelocity;
  84793. if (!v) {
  84794. return null;
  84795. }
  84796. return new BABYLON.Vector3(v.x, v.y, v.z);
  84797. };
  84798. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84799. impostor.physicsBody.mass = mass;
  84800. impostor.physicsBody.updateMassProperties();
  84801. };
  84802. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84803. return impostor.physicsBody.mass;
  84804. };
  84805. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84806. return impostor.physicsBody.material.friction;
  84807. };
  84808. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84809. impostor.physicsBody.material.friction = friction;
  84810. };
  84811. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84812. return impostor.physicsBody.material.restitution;
  84813. };
  84814. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84815. impostor.physicsBody.material.restitution = restitution;
  84816. };
  84817. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84818. impostor.physicsBody.sleep();
  84819. };
  84820. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84821. impostor.physicsBody.wakeUp();
  84822. };
  84823. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84824. joint.physicsJoint.distance = maxDistance;
  84825. };
  84826. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84827. // if (!motorIndex) {
  84828. // joint.physicsJoint.enableMotor();
  84829. // }
  84830. // }
  84831. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84832. // if (!motorIndex) {
  84833. // joint.physicsJoint.disableMotor();
  84834. // }
  84835. // }
  84836. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84837. if (!motorIndex) {
  84838. joint.physicsJoint.enableMotor();
  84839. joint.physicsJoint.setMotorSpeed(speed);
  84840. if (maxForce) {
  84841. this.setLimit(joint, maxForce);
  84842. }
  84843. }
  84844. };
  84845. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84846. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84847. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84848. };
  84849. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84850. var body = impostor.physicsBody;
  84851. mesh.position.x = body.position.x;
  84852. mesh.position.y = body.position.y;
  84853. mesh.position.z = body.position.z;
  84854. if (mesh.rotationQuaternion) {
  84855. mesh.rotationQuaternion.x = body.quaternion.x;
  84856. mesh.rotationQuaternion.y = body.quaternion.y;
  84857. mesh.rotationQuaternion.z = body.quaternion.z;
  84858. mesh.rotationQuaternion.w = body.quaternion.w;
  84859. }
  84860. };
  84861. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84862. var shape = impostor.physicsBody.shapes[0];
  84863. return shape.boundingSphereRadius;
  84864. };
  84865. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84866. var shape = impostor.physicsBody.shapes[0];
  84867. result.x = shape.halfExtents.x * 2;
  84868. result.y = shape.halfExtents.y * 2;
  84869. result.z = shape.halfExtents.z * 2;
  84870. };
  84871. CannonJSPlugin.prototype.dispose = function () {
  84872. };
  84873. CannonJSPlugin.prototype._extendNamespace = function () {
  84874. //this will force cannon to execute at least one step when using interpolation
  84875. var step_tmp1 = new this.BJSCANNON.Vec3();
  84876. var Engine = this.BJSCANNON;
  84877. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84878. maxSubSteps = maxSubSteps || 10;
  84879. timeSinceLastCalled = timeSinceLastCalled || 0;
  84880. if (timeSinceLastCalled === 0) {
  84881. this.internalStep(dt);
  84882. this.time += dt;
  84883. }
  84884. else {
  84885. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84886. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84887. var t0 = performance.now();
  84888. for (var i = 0; i !== internalSteps; i++) {
  84889. this.internalStep(dt);
  84890. if (performance.now() - t0 > dt * 1000) {
  84891. break;
  84892. }
  84893. }
  84894. this.time += timeSinceLastCalled;
  84895. var h = this.time % dt;
  84896. var h_div_dt = h / dt;
  84897. var interpvelo = step_tmp1;
  84898. var bodies = this.bodies;
  84899. for (var j = 0; j !== bodies.length; j++) {
  84900. var b = bodies[j];
  84901. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84902. b.position.vsub(b.previousPosition, interpvelo);
  84903. interpvelo.scale(h_div_dt, interpvelo);
  84904. b.position.vadd(interpvelo, b.interpolatedPosition);
  84905. }
  84906. else {
  84907. b.interpolatedPosition.copy(b.position);
  84908. b.interpolatedQuaternion.copy(b.quaternion);
  84909. }
  84910. }
  84911. }
  84912. };
  84913. };
  84914. return CannonJSPlugin;
  84915. }());
  84916. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84917. })(BABYLON || (BABYLON = {}));
  84918. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84919. var BABYLON;
  84920. (function (BABYLON) {
  84921. var OimoJSPlugin = /** @class */ (function () {
  84922. function OimoJSPlugin(iterations) {
  84923. this.name = "OimoJSPlugin";
  84924. this._tmpImpostorsArray = [];
  84925. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84926. this.BJSOIMO = OIMO;
  84927. this.world = new this.BJSOIMO.World({
  84928. iterations: iterations
  84929. });
  84930. this.world.clear();
  84931. }
  84932. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84933. this.world.gravity.copy(gravity);
  84934. };
  84935. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84936. this.world.timeStep = timeStep;
  84937. };
  84938. OimoJSPlugin.prototype.getTimeStep = function () {
  84939. return this.world.timeStep;
  84940. };
  84941. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84942. var _this = this;
  84943. impostors.forEach(function (impostor) {
  84944. impostor.beforeStep();
  84945. });
  84946. this.world.step();
  84947. impostors.forEach(function (impostor) {
  84948. impostor.afterStep();
  84949. //update the ordered impostors array
  84950. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84951. });
  84952. //check for collisions
  84953. var contact = this.world.contacts;
  84954. while (contact !== null) {
  84955. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84956. contact = contact.next;
  84957. continue;
  84958. }
  84959. //is this body colliding with any other? get the impostor
  84960. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84961. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84962. if (!mainImpostor || !collidingImpostor) {
  84963. contact = contact.next;
  84964. continue;
  84965. }
  84966. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84967. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84968. contact = contact.next;
  84969. }
  84970. };
  84971. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84972. var mass = impostor.physicsBody.mass;
  84973. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84974. };
  84975. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84976. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84977. this.applyImpulse(impostor, force, contactPoint);
  84978. };
  84979. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84980. var _this = this;
  84981. //parent-child relationship. Does this impostor has a parent impostor?
  84982. if (impostor.parent) {
  84983. if (impostor.physicsBody) {
  84984. this.removePhysicsBody(impostor);
  84985. //TODO is that needed?
  84986. impostor.forceUpdate();
  84987. }
  84988. return;
  84989. }
  84990. if (impostor.isBodyInitRequired()) {
  84991. var bodyConfig = {
  84992. name: impostor.uniqueId,
  84993. //Oimo must have mass, also for static objects.
  84994. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84995. size: [],
  84996. type: [],
  84997. pos: [],
  84998. posShape: [],
  84999. rot: [],
  85000. rotShape: [],
  85001. move: impostor.getParam("mass") !== 0,
  85002. density: impostor.getParam("mass"),
  85003. friction: impostor.getParam("friction"),
  85004. restitution: impostor.getParam("restitution"),
  85005. //Supporting older versions of Oimo
  85006. world: this.world
  85007. };
  85008. var impostors = [impostor];
  85009. var addToArray = function (parent) {
  85010. if (!parent.getChildMeshes)
  85011. return;
  85012. parent.getChildMeshes().forEach(function (m) {
  85013. if (m.physicsImpostor) {
  85014. impostors.push(m.physicsImpostor);
  85015. //m.physicsImpostor._init();
  85016. }
  85017. });
  85018. };
  85019. addToArray(impostor.object);
  85020. var checkWithEpsilon_1 = function (value) {
  85021. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85022. };
  85023. impostors.forEach(function (i) {
  85024. if (!i.object.rotationQuaternion) {
  85025. return;
  85026. }
  85027. //get the correct bounding box
  85028. var oldQuaternion = i.object.rotationQuaternion;
  85029. var rot = oldQuaternion.toEulerAngles();
  85030. var extendSize = i.getObjectExtendSize();
  85031. var radToDeg = 57.295779513082320876;
  85032. if (i === impostor) {
  85033. var center = impostor.getObjectCenter();
  85034. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85035. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85036. //Can also use Array.prototype.push.apply
  85037. bodyConfig.pos.push(center.x);
  85038. bodyConfig.pos.push(center.y);
  85039. bodyConfig.pos.push(center.z);
  85040. bodyConfig.posShape.push(0, 0, 0);
  85041. //tmp solution
  85042. bodyConfig.rot.push(rot.x * radToDeg);
  85043. bodyConfig.rot.push(rot.y * radToDeg);
  85044. bodyConfig.rot.push(rot.z * radToDeg);
  85045. bodyConfig.rotShape.push(0, 0, 0);
  85046. }
  85047. else {
  85048. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85049. bodyConfig.posShape.push(localPosition.x);
  85050. bodyConfig.posShape.push(localPosition.y);
  85051. bodyConfig.posShape.push(localPosition.z);
  85052. bodyConfig.pos.push(0, 0, 0);
  85053. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85054. bodyConfig.rot.push(0);
  85055. bodyConfig.rot.push(0);
  85056. bodyConfig.rot.push(0);
  85057. bodyConfig.rotShape.push(rot.x * radToDeg);
  85058. bodyConfig.rotShape.push(rot.y * radToDeg);
  85059. bodyConfig.rotShape.push(rot.z * radToDeg);
  85060. }
  85061. // register mesh
  85062. switch (i.type) {
  85063. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85064. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85065. case BABYLON.PhysicsImpostor.SphereImpostor:
  85066. var radiusX = extendSize.x;
  85067. var radiusY = extendSize.y;
  85068. var radiusZ = extendSize.z;
  85069. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85070. bodyConfig.type.push('sphere');
  85071. //due to the way oimo works with compounds, add 3 times
  85072. bodyConfig.size.push(size);
  85073. bodyConfig.size.push(size);
  85074. bodyConfig.size.push(size);
  85075. break;
  85076. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85077. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85078. var sizeY = checkWithEpsilon_1(extendSize.y);
  85079. bodyConfig.type.push('cylinder');
  85080. bodyConfig.size.push(sizeX);
  85081. bodyConfig.size.push(sizeY);
  85082. //due to the way oimo works with compounds, add one more value.
  85083. bodyConfig.size.push(sizeY);
  85084. break;
  85085. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85086. case BABYLON.PhysicsImpostor.BoxImpostor:
  85087. default:
  85088. var sizeX = checkWithEpsilon_1(extendSize.x);
  85089. var sizeY = checkWithEpsilon_1(extendSize.y);
  85090. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85091. bodyConfig.type.push('box');
  85092. //if (i === impostor) {
  85093. bodyConfig.size.push(sizeX);
  85094. bodyConfig.size.push(sizeY);
  85095. bodyConfig.size.push(sizeZ);
  85096. //} else {
  85097. // bodyConfig.size.push(0,0,0);
  85098. //}
  85099. break;
  85100. }
  85101. //actually not needed, but hey...
  85102. i.object.rotationQuaternion = oldQuaternion;
  85103. });
  85104. impostor.physicsBody = this.world.add(bodyConfig);
  85105. }
  85106. else {
  85107. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85108. }
  85109. impostor.setDeltaPosition(this._tmpPositionVector);
  85110. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85111. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85112. };
  85113. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85114. //impostor.physicsBody.dispose();
  85115. //Same as : (older oimo versions)
  85116. this.world.removeRigidBody(impostor.physicsBody);
  85117. };
  85118. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85119. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85120. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85121. if (!mainBody || !connectedBody) {
  85122. return;
  85123. }
  85124. var jointData = impostorJoint.joint.jointData;
  85125. var options = jointData.nativeParams || {};
  85126. var type;
  85127. var nativeJointData = {
  85128. body1: mainBody,
  85129. body2: connectedBody,
  85130. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85131. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85132. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85133. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85134. min: options.min,
  85135. max: options.max,
  85136. collision: options.collision || jointData.collision,
  85137. spring: options.spring,
  85138. //supporting older version of Oimo
  85139. world: this.world
  85140. };
  85141. switch (impostorJoint.joint.type) {
  85142. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85143. type = "jointBall";
  85144. break;
  85145. case BABYLON.PhysicsJoint.SpringJoint:
  85146. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85147. var springData = jointData;
  85148. nativeJointData.min = springData.length || nativeJointData.min;
  85149. //Max should also be set, just make sure it is at least min
  85150. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85151. case BABYLON.PhysicsJoint.DistanceJoint:
  85152. type = "jointDistance";
  85153. nativeJointData.max = jointData.maxDistance;
  85154. break;
  85155. case BABYLON.PhysicsJoint.PrismaticJoint:
  85156. type = "jointPrisme";
  85157. break;
  85158. case BABYLON.PhysicsJoint.SliderJoint:
  85159. type = "jointSlide";
  85160. break;
  85161. case BABYLON.PhysicsJoint.WheelJoint:
  85162. type = "jointWheel";
  85163. break;
  85164. case BABYLON.PhysicsJoint.HingeJoint:
  85165. default:
  85166. type = "jointHinge";
  85167. break;
  85168. }
  85169. nativeJointData.type = type;
  85170. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85171. };
  85172. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85173. //Bug in Oimo prevents us from disposing a joint in the playground
  85174. //joint.joint.physicsJoint.dispose();
  85175. //So we will bruteforce it!
  85176. try {
  85177. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85178. }
  85179. catch (e) {
  85180. BABYLON.Tools.Warn(e);
  85181. }
  85182. };
  85183. OimoJSPlugin.prototype.isSupported = function () {
  85184. return this.BJSOIMO !== undefined;
  85185. };
  85186. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85187. if (!impostor.physicsBody.sleeping) {
  85188. //TODO check that
  85189. /*if (impostor.physicsBody.shapes.next) {
  85190. var parentShape = this._getLastShape(impostor.physicsBody);
  85191. impostor.object.position.copyFrom(parentShape.position);
  85192. console.log(parentShape.position);
  85193. } else {*/
  85194. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85195. //}
  85196. if (impostor.object.rotationQuaternion) {
  85197. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85198. }
  85199. }
  85200. };
  85201. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85202. var body = impostor.physicsBody;
  85203. body.position.copy(newPosition);
  85204. body.orientation.copy(newRotation);
  85205. body.syncShapes();
  85206. body.awake();
  85207. };
  85208. /*private _getLastShape(body: any): any {
  85209. var lastShape = body.shapes;
  85210. while (lastShape.next) {
  85211. lastShape = lastShape.next;
  85212. }
  85213. return lastShape;
  85214. }*/
  85215. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85216. impostor.physicsBody.linearVelocity.copy(velocity);
  85217. };
  85218. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85219. impostor.physicsBody.angularVelocity.copy(velocity);
  85220. };
  85221. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85222. var v = impostor.physicsBody.linearVelocity;
  85223. if (!v) {
  85224. return null;
  85225. }
  85226. return new BABYLON.Vector3(v.x, v.y, v.z);
  85227. };
  85228. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85229. var v = impostor.physicsBody.angularVelocity;
  85230. if (!v) {
  85231. return null;
  85232. }
  85233. return new BABYLON.Vector3(v.x, v.y, v.z);
  85234. };
  85235. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85236. var staticBody = mass === 0;
  85237. //this will actually set the body's density and not its mass.
  85238. //But this is how oimo treats the mass variable.
  85239. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85240. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85241. };
  85242. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85243. return impostor.physicsBody.shapes.density;
  85244. };
  85245. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85246. return impostor.physicsBody.shapes.friction;
  85247. };
  85248. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85249. impostor.physicsBody.shapes.friction = friction;
  85250. };
  85251. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85252. return impostor.physicsBody.shapes.restitution;
  85253. };
  85254. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85255. impostor.physicsBody.shapes.restitution = restitution;
  85256. };
  85257. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85258. impostor.physicsBody.sleep();
  85259. };
  85260. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85261. impostor.physicsBody.awake();
  85262. };
  85263. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85264. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85265. if (minDistance !== void 0) {
  85266. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85267. }
  85268. };
  85269. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85270. //TODO separate rotational and transational motors.
  85271. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85272. if (motor) {
  85273. motor.setMotor(speed, maxForce);
  85274. }
  85275. };
  85276. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85277. //TODO separate rotational and transational motors.
  85278. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85279. if (motor) {
  85280. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85281. }
  85282. };
  85283. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85284. var body = impostor.physicsBody;
  85285. mesh.position.x = body.position.x;
  85286. mesh.position.y = body.position.y;
  85287. mesh.position.z = body.position.z;
  85288. if (mesh.rotationQuaternion) {
  85289. mesh.rotationQuaternion.x = body.orientation.x;
  85290. mesh.rotationQuaternion.y = body.orientation.y;
  85291. mesh.rotationQuaternion.z = body.orientation.z;
  85292. mesh.rotationQuaternion.w = body.orientation.s;
  85293. }
  85294. };
  85295. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85296. return impostor.physicsBody.shapes.radius;
  85297. };
  85298. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85299. var shape = impostor.physicsBody.shapes;
  85300. result.x = shape.halfWidth * 2;
  85301. result.y = shape.halfHeight * 2;
  85302. result.z = shape.halfDepth * 2;
  85303. };
  85304. OimoJSPlugin.prototype.dispose = function () {
  85305. this.world.clear();
  85306. };
  85307. return OimoJSPlugin;
  85308. }());
  85309. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85310. })(BABYLON || (BABYLON = {}));
  85311. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85312. var BABYLON;
  85313. (function (BABYLON) {
  85314. /*
  85315. * Based on jsTGALoader - Javascript loader for TGA file
  85316. * By Vincent Thibault
  85317. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85318. */
  85319. var TGATools = /** @class */ (function () {
  85320. function TGATools() {
  85321. }
  85322. TGATools.GetTGAHeader = function (data) {
  85323. var offset = 0;
  85324. var header = {
  85325. id_length: data[offset++],
  85326. colormap_type: data[offset++],
  85327. image_type: data[offset++],
  85328. colormap_index: data[offset++] | data[offset++] << 8,
  85329. colormap_length: data[offset++] | data[offset++] << 8,
  85330. colormap_size: data[offset++],
  85331. origin: [
  85332. data[offset++] | data[offset++] << 8,
  85333. data[offset++] | data[offset++] << 8
  85334. ],
  85335. width: data[offset++] | data[offset++] << 8,
  85336. height: data[offset++] | data[offset++] << 8,
  85337. pixel_size: data[offset++],
  85338. flags: data[offset++]
  85339. };
  85340. return header;
  85341. };
  85342. TGATools.UploadContent = function (gl, data) {
  85343. // Not enough data to contain header ?
  85344. if (data.length < 19) {
  85345. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85346. return;
  85347. }
  85348. // Read Header
  85349. var offset = 18;
  85350. var header = TGATools.GetTGAHeader(data);
  85351. // Assume it's a valid Targa file.
  85352. if (header.id_length + offset > data.length) {
  85353. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85354. return;
  85355. }
  85356. // Skip not needed data
  85357. offset += header.id_length;
  85358. var use_rle = false;
  85359. var use_pal = false;
  85360. var use_grey = false;
  85361. // Get some informations.
  85362. switch (header.image_type) {
  85363. case TGATools._TYPE_RLE_INDEXED:
  85364. use_rle = true;
  85365. case TGATools._TYPE_INDEXED:
  85366. use_pal = true;
  85367. break;
  85368. case TGATools._TYPE_RLE_RGB:
  85369. use_rle = true;
  85370. case TGATools._TYPE_RGB:
  85371. // use_rgb = true;
  85372. break;
  85373. case TGATools._TYPE_RLE_GREY:
  85374. use_rle = true;
  85375. case TGATools._TYPE_GREY:
  85376. use_grey = true;
  85377. break;
  85378. }
  85379. var pixel_data;
  85380. // var numAlphaBits = header.flags & 0xf;
  85381. var pixel_size = header.pixel_size >> 3;
  85382. var pixel_total = header.width * header.height * pixel_size;
  85383. // Read palettes
  85384. var palettes;
  85385. if (use_pal) {
  85386. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85387. }
  85388. // Read LRE
  85389. if (use_rle) {
  85390. pixel_data = new Uint8Array(pixel_total);
  85391. var c, count, i;
  85392. var localOffset = 0;
  85393. var pixels = new Uint8Array(pixel_size);
  85394. while (offset < pixel_total && localOffset < pixel_total) {
  85395. c = data[offset++];
  85396. count = (c & 0x7f) + 1;
  85397. // RLE pixels
  85398. if (c & 0x80) {
  85399. // Bind pixel tmp array
  85400. for (i = 0; i < pixel_size; ++i) {
  85401. pixels[i] = data[offset++];
  85402. }
  85403. // Copy pixel array
  85404. for (i = 0; i < count; ++i) {
  85405. pixel_data.set(pixels, localOffset + i * pixel_size);
  85406. }
  85407. localOffset += pixel_size * count;
  85408. }
  85409. // Raw pixels
  85410. else {
  85411. count *= pixel_size;
  85412. for (i = 0; i < count; ++i) {
  85413. pixel_data[localOffset + i] = data[offset++];
  85414. }
  85415. localOffset += count;
  85416. }
  85417. }
  85418. }
  85419. // RAW Pixels
  85420. else {
  85421. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85422. }
  85423. // Load to texture
  85424. var x_start, y_start, x_step, y_step, y_end, x_end;
  85425. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85426. default:
  85427. case TGATools._ORIGIN_UL:
  85428. x_start = 0;
  85429. x_step = 1;
  85430. x_end = header.width;
  85431. y_start = 0;
  85432. y_step = 1;
  85433. y_end = header.height;
  85434. break;
  85435. case TGATools._ORIGIN_BL:
  85436. x_start = 0;
  85437. x_step = 1;
  85438. x_end = header.width;
  85439. y_start = header.height - 1;
  85440. y_step = -1;
  85441. y_end = -1;
  85442. break;
  85443. case TGATools._ORIGIN_UR:
  85444. x_start = header.width - 1;
  85445. x_step = -1;
  85446. x_end = -1;
  85447. y_start = 0;
  85448. y_step = 1;
  85449. y_end = header.height;
  85450. break;
  85451. case TGATools._ORIGIN_BR:
  85452. x_start = header.width - 1;
  85453. x_step = -1;
  85454. x_end = -1;
  85455. y_start = header.height - 1;
  85456. y_step = -1;
  85457. y_end = -1;
  85458. break;
  85459. }
  85460. // Load the specify method
  85461. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85462. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85463. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85464. };
  85465. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85466. var image = pixel_data, colormap = palettes;
  85467. var width = header.width, height = header.height;
  85468. var color, i = 0, x, y;
  85469. var imageData = new Uint8Array(width * height * 4);
  85470. for (y = y_start; y !== y_end; y += y_step) {
  85471. for (x = x_start; x !== x_end; x += x_step, i++) {
  85472. color = image[i];
  85473. imageData[(x + width * y) * 4 + 3] = 255;
  85474. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85475. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85476. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85477. }
  85478. }
  85479. return imageData;
  85480. };
  85481. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85482. var image = pixel_data;
  85483. var width = header.width, height = header.height;
  85484. var color, i = 0, x, y;
  85485. var imageData = new Uint8Array(width * height * 4);
  85486. for (y = y_start; y !== y_end; y += y_step) {
  85487. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85488. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85489. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85490. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85491. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85492. imageData[(x + width * y) * 4 + 0] = r;
  85493. imageData[(x + width * y) * 4 + 1] = g;
  85494. imageData[(x + width * y) * 4 + 2] = b;
  85495. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85496. }
  85497. }
  85498. return imageData;
  85499. };
  85500. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85501. var image = pixel_data;
  85502. var width = header.width, height = header.height;
  85503. var i = 0, x, y;
  85504. var imageData = new Uint8Array(width * height * 4);
  85505. for (y = y_start; y !== y_end; y += y_step) {
  85506. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85507. imageData[(x + width * y) * 4 + 3] = 255;
  85508. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85509. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85510. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85511. }
  85512. }
  85513. return imageData;
  85514. };
  85515. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85516. var image = pixel_data;
  85517. var width = header.width, height = header.height;
  85518. var i = 0, x, y;
  85519. var imageData = new Uint8Array(width * height * 4);
  85520. for (y = y_start; y !== y_end; y += y_step) {
  85521. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85522. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85523. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85524. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85525. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85526. }
  85527. }
  85528. return imageData;
  85529. };
  85530. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85531. var image = pixel_data;
  85532. var width = header.width, height = header.height;
  85533. var color, i = 0, x, y;
  85534. var imageData = new Uint8Array(width * height * 4);
  85535. for (y = y_start; y !== y_end; y += y_step) {
  85536. for (x = x_start; x !== x_end; x += x_step, i++) {
  85537. color = image[i];
  85538. imageData[(x + width * y) * 4 + 0] = color;
  85539. imageData[(x + width * y) * 4 + 1] = color;
  85540. imageData[(x + width * y) * 4 + 2] = color;
  85541. imageData[(x + width * y) * 4 + 3] = 255;
  85542. }
  85543. }
  85544. return imageData;
  85545. };
  85546. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85547. var image = pixel_data;
  85548. var width = header.width, height = header.height;
  85549. var i = 0, x, y;
  85550. var imageData = new Uint8Array(width * height * 4);
  85551. for (y = y_start; y !== y_end; y += y_step) {
  85552. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85553. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85554. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85555. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85556. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85557. }
  85558. }
  85559. return imageData;
  85560. };
  85561. //private static _TYPE_NO_DATA = 0;
  85562. TGATools._TYPE_INDEXED = 1;
  85563. TGATools._TYPE_RGB = 2;
  85564. TGATools._TYPE_GREY = 3;
  85565. TGATools._TYPE_RLE_INDEXED = 9;
  85566. TGATools._TYPE_RLE_RGB = 10;
  85567. TGATools._TYPE_RLE_GREY = 11;
  85568. TGATools._ORIGIN_MASK = 0x30;
  85569. TGATools._ORIGIN_SHIFT = 0x04;
  85570. TGATools._ORIGIN_BL = 0x00;
  85571. TGATools._ORIGIN_BR = 0x01;
  85572. TGATools._ORIGIN_UL = 0x02;
  85573. TGATools._ORIGIN_UR = 0x03;
  85574. return TGATools;
  85575. }());
  85576. BABYLON.TGATools = TGATools;
  85577. })(BABYLON || (BABYLON = {}));
  85578. //# sourceMappingURL=babylon.tga.js.map
  85579. var BABYLON;
  85580. (function (BABYLON) {
  85581. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85582. // All values and structures referenced from:
  85583. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85584. var DDS_MAGIC = 0x20534444;
  85585. var
  85586. //DDSD_CAPS = 0x1,
  85587. //DDSD_HEIGHT = 0x2,
  85588. //DDSD_WIDTH = 0x4,
  85589. //DDSD_PITCH = 0x8,
  85590. //DDSD_PIXELFORMAT = 0x1000,
  85591. DDSD_MIPMAPCOUNT = 0x20000;
  85592. //DDSD_LINEARSIZE = 0x80000,
  85593. //DDSD_DEPTH = 0x800000;
  85594. // var DDSCAPS_COMPLEX = 0x8,
  85595. // DDSCAPS_MIPMAP = 0x400000,
  85596. // DDSCAPS_TEXTURE = 0x1000;
  85597. var DDSCAPS2_CUBEMAP = 0x200;
  85598. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85599. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85600. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85601. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85602. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85603. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85604. // DDSCAPS2_VOLUME = 0x200000;
  85605. var
  85606. //DDPF_ALPHAPIXELS = 0x1,
  85607. //DDPF_ALPHA = 0x2,
  85608. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85609. //DDPF_YUV = 0x200,
  85610. DDPF_LUMINANCE = 0x20000;
  85611. function FourCCToInt32(value) {
  85612. return value.charCodeAt(0) +
  85613. (value.charCodeAt(1) << 8) +
  85614. (value.charCodeAt(2) << 16) +
  85615. (value.charCodeAt(3) << 24);
  85616. }
  85617. function Int32ToFourCC(value) {
  85618. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85619. }
  85620. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85621. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85622. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85623. var FOURCC_DX10 = FourCCToInt32("DX10");
  85624. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85625. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85626. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85627. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85628. var headerLengthInt = 31; // The header length in 32 bit ints
  85629. // Offsets into the header array
  85630. var off_magic = 0;
  85631. var off_size = 1;
  85632. var off_flags = 2;
  85633. var off_height = 3;
  85634. var off_width = 4;
  85635. var off_mipmapCount = 7;
  85636. var off_pfFlags = 20;
  85637. var off_pfFourCC = 21;
  85638. var off_RGBbpp = 22;
  85639. var off_RMask = 23;
  85640. var off_GMask = 24;
  85641. var off_BMask = 25;
  85642. var off_AMask = 26;
  85643. // var off_caps1 = 27;
  85644. var off_caps2 = 28;
  85645. // var off_caps3 = 29;
  85646. // var off_caps4 = 30;
  85647. var off_dxgiFormat = 32;
  85648. ;
  85649. var DDSTools = /** @class */ (function () {
  85650. function DDSTools() {
  85651. }
  85652. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85653. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85654. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85655. var mipmapCount = 1;
  85656. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85657. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85658. }
  85659. var fourCC = header[off_pfFourCC];
  85660. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85661. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85662. switch (fourCC) {
  85663. case FOURCC_D3DFMT_R16G16B16A16F:
  85664. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85665. break;
  85666. case FOURCC_D3DFMT_R32G32B32A32F:
  85667. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85668. break;
  85669. case FOURCC_DX10:
  85670. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85671. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85672. break;
  85673. }
  85674. }
  85675. return {
  85676. width: header[off_width],
  85677. height: header[off_height],
  85678. mipmapCount: mipmapCount,
  85679. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85680. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85681. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85682. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85683. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85684. dxgiFormat: dxgiFormat,
  85685. textureType: textureType
  85686. };
  85687. };
  85688. DDSTools._ToHalfFloat = function (value) {
  85689. if (!DDSTools._FloatView) {
  85690. DDSTools._FloatView = new Float32Array(1);
  85691. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85692. }
  85693. DDSTools._FloatView[0] = value;
  85694. var x = DDSTools._Int32View[0];
  85695. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85696. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85697. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85698. /* If zero, or denormal, or exponent underflows too much for a denormal
  85699. * half, return signed zero. */
  85700. if (e < 103) {
  85701. return bits;
  85702. }
  85703. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85704. if (e > 142) {
  85705. bits |= 0x7c00;
  85706. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85707. * not Inf, so make sure we set one mantissa bit too. */
  85708. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85709. return bits;
  85710. }
  85711. /* If exponent underflows but not too much, return a denormal */
  85712. if (e < 113) {
  85713. m |= 0x0800;
  85714. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85715. * to 1, which is OK. */
  85716. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85717. return bits;
  85718. }
  85719. bits |= ((e - 112) << 10) | (m >> 1);
  85720. bits += m & 1;
  85721. return bits;
  85722. };
  85723. DDSTools._FromHalfFloat = function (value) {
  85724. var s = (value & 0x8000) >> 15;
  85725. var e = (value & 0x7C00) >> 10;
  85726. var f = value & 0x03FF;
  85727. if (e === 0) {
  85728. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85729. }
  85730. else if (e == 0x1F) {
  85731. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85732. }
  85733. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85734. };
  85735. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85736. var destArray = new Float32Array(dataLength);
  85737. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85738. var index = 0;
  85739. for (var y = 0; y < height; y++) {
  85740. for (var x = 0; x < width; x++) {
  85741. var srcPos = (x + y * width) * 4;
  85742. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85743. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85744. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85745. if (DDSTools.StoreLODInAlphaChannel) {
  85746. destArray[index + 3] = lod;
  85747. }
  85748. else {
  85749. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85750. }
  85751. index += 4;
  85752. }
  85753. }
  85754. return destArray;
  85755. };
  85756. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85757. if (DDSTools.StoreLODInAlphaChannel) {
  85758. var destArray = new Uint16Array(dataLength);
  85759. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85760. var index = 0;
  85761. for (var y = 0; y < height; y++) {
  85762. for (var x = 0; x < width; x++) {
  85763. var srcPos = (x + y * width) * 4;
  85764. destArray[index] = srcData[srcPos];
  85765. destArray[index + 1] = srcData[srcPos + 1];
  85766. destArray[index + 2] = srcData[srcPos + 2];
  85767. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85768. index += 4;
  85769. }
  85770. }
  85771. return destArray;
  85772. }
  85773. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85774. };
  85775. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85776. if (DDSTools.StoreLODInAlphaChannel) {
  85777. var destArray = new Float32Array(dataLength);
  85778. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85779. var index = 0;
  85780. for (var y = 0; y < height; y++) {
  85781. for (var x = 0; x < width; x++) {
  85782. var srcPos = (x + y * width) * 4;
  85783. destArray[index] = srcData[srcPos];
  85784. destArray[index + 1] = srcData[srcPos + 1];
  85785. destArray[index + 2] = srcData[srcPos + 2];
  85786. destArray[index + 3] = lod;
  85787. index += 4;
  85788. }
  85789. }
  85790. return destArray;
  85791. }
  85792. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85793. };
  85794. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85795. var destArray = new Uint8Array(dataLength);
  85796. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85797. var index = 0;
  85798. for (var y = 0; y < height; y++) {
  85799. for (var x = 0; x < width; x++) {
  85800. var srcPos = (x + y * width) * 4;
  85801. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85802. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85803. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85804. if (DDSTools.StoreLODInAlphaChannel) {
  85805. destArray[index + 3] = lod;
  85806. }
  85807. else {
  85808. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85809. }
  85810. index += 4;
  85811. }
  85812. }
  85813. return destArray;
  85814. };
  85815. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85816. var destArray = new Uint8Array(dataLength);
  85817. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85818. var index = 0;
  85819. for (var y = 0; y < height; y++) {
  85820. for (var x = 0; x < width; x++) {
  85821. var srcPos = (x + y * width) * 4;
  85822. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85823. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85824. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85825. if (DDSTools.StoreLODInAlphaChannel) {
  85826. destArray[index + 3] = lod;
  85827. }
  85828. else {
  85829. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85830. }
  85831. index += 4;
  85832. }
  85833. }
  85834. return destArray;
  85835. };
  85836. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85837. var byteArray = new Uint8Array(dataLength);
  85838. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85839. var index = 0;
  85840. for (var y = 0; y < height; y++) {
  85841. for (var x = 0; x < width; x++) {
  85842. var srcPos = (x + y * width) * 4;
  85843. byteArray[index] = srcData[srcPos + rOffset];
  85844. byteArray[index + 1] = srcData[srcPos + gOffset];
  85845. byteArray[index + 2] = srcData[srcPos + bOffset];
  85846. byteArray[index + 3] = srcData[srcPos + aOffset];
  85847. index += 4;
  85848. }
  85849. }
  85850. return byteArray;
  85851. };
  85852. DDSTools._ExtractLongWordOrder = function (value) {
  85853. if (value === 0 || value === 255 || value === -16777216) {
  85854. return 0;
  85855. }
  85856. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85857. };
  85858. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85859. var byteArray = new Uint8Array(dataLength);
  85860. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85861. var index = 0;
  85862. for (var y = 0; y < height; y++) {
  85863. for (var x = 0; x < width; x++) {
  85864. var srcPos = (x + y * width) * 3;
  85865. byteArray[index] = srcData[srcPos + rOffset];
  85866. byteArray[index + 1] = srcData[srcPos + gOffset];
  85867. byteArray[index + 2] = srcData[srcPos + bOffset];
  85868. index += 3;
  85869. }
  85870. }
  85871. return byteArray;
  85872. };
  85873. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85874. var byteArray = new Uint8Array(dataLength);
  85875. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85876. var index = 0;
  85877. for (var y = 0; y < height; y++) {
  85878. for (var x = 0; x < width; x++) {
  85879. var srcPos = (x + y * width);
  85880. byteArray[index] = srcData[srcPos];
  85881. index++;
  85882. }
  85883. }
  85884. return byteArray;
  85885. };
  85886. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85887. if (lodIndex === void 0) { lodIndex = -1; }
  85888. var sphericalPolynomialFaces = null;
  85889. if (info.sphericalPolynomial) {
  85890. sphericalPolynomialFaces = new Array();
  85891. }
  85892. var ext = engine.getCaps().s3tc;
  85893. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85894. var fourCC, width, height, dataLength = 0, dataOffset;
  85895. var byteArray, mipmapCount, mip;
  85896. var internalFormat = 0;
  85897. var format = 0;
  85898. var blockBytes = 1;
  85899. if (header[off_magic] !== DDS_MAGIC) {
  85900. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85901. return;
  85902. }
  85903. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85904. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85905. return;
  85906. }
  85907. if (info.isCompressed && !ext) {
  85908. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85909. return;
  85910. }
  85911. var bpp = header[off_RGBbpp];
  85912. dataOffset = header[off_size] + 4;
  85913. var computeFormats = false;
  85914. if (info.isFourCC) {
  85915. fourCC = header[off_pfFourCC];
  85916. switch (fourCC) {
  85917. case FOURCC_DXT1:
  85918. blockBytes = 8;
  85919. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85920. break;
  85921. case FOURCC_DXT3:
  85922. blockBytes = 16;
  85923. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85924. break;
  85925. case FOURCC_DXT5:
  85926. blockBytes = 16;
  85927. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85928. break;
  85929. case FOURCC_D3DFMT_R16G16B16A16F:
  85930. computeFormats = true;
  85931. break;
  85932. case FOURCC_D3DFMT_R32G32B32A32F:
  85933. computeFormats = true;
  85934. break;
  85935. case FOURCC_DX10:
  85936. // There is an additionnal header so dataOffset need to be changed
  85937. dataOffset += 5 * 4; // 5 uints
  85938. var supported = false;
  85939. switch (info.dxgiFormat) {
  85940. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85941. computeFormats = true;
  85942. supported = true;
  85943. break;
  85944. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85945. info.isRGB = true;
  85946. info.isFourCC = false;
  85947. bpp = 32;
  85948. supported = true;
  85949. break;
  85950. }
  85951. if (supported) {
  85952. break;
  85953. }
  85954. default:
  85955. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85956. return;
  85957. }
  85958. }
  85959. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85960. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85961. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85962. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85963. if (computeFormats) {
  85964. format = engine._getWebGLTextureType(info.textureType);
  85965. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85966. }
  85967. mipmapCount = 1;
  85968. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85969. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85970. }
  85971. for (var face = 0; face < faces; face++) {
  85972. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85973. width = header[off_width];
  85974. height = header[off_height];
  85975. for (mip = 0; mip < mipmapCount; ++mip) {
  85976. if (lodIndex === -1 || lodIndex === mip) {
  85977. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85978. var i = (lodIndex === -1) ? mip : 0;
  85979. if (!info.isCompressed && info.isFourCC) {
  85980. dataLength = width * height * 4;
  85981. var floatArray = null;
  85982. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85983. if (bpp === 128) {
  85984. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85985. if (sphericalPolynomialFaces && i == 0) {
  85986. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85987. }
  85988. }
  85989. else if (bpp === 64) {
  85990. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85991. if (sphericalPolynomialFaces && i == 0) {
  85992. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85993. }
  85994. }
  85995. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85996. format = engine._getWebGLTextureType(info.textureType);
  85997. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85998. }
  85999. else {
  86000. if (bpp === 128) {
  86001. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86002. if (sphericalPolynomialFaces && i == 0) {
  86003. sphericalPolynomialFaces.push(floatArray);
  86004. }
  86005. }
  86006. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86007. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86008. if (sphericalPolynomialFaces && i == 0) {
  86009. sphericalPolynomialFaces.push(floatArray);
  86010. }
  86011. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86012. format = engine._getWebGLTextureType(info.textureType);
  86013. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86014. }
  86015. else { // 64
  86016. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86017. if (sphericalPolynomialFaces && i == 0) {
  86018. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86019. }
  86020. }
  86021. }
  86022. if (floatArray) {
  86023. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86024. }
  86025. }
  86026. else if (info.isRGB) {
  86027. if (bpp === 24) {
  86028. dataLength = width * height * 3;
  86029. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86030. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86031. }
  86032. else { // 32
  86033. dataLength = width * height * 4;
  86034. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86035. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86036. }
  86037. }
  86038. else if (info.isLuminance) {
  86039. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86040. var unpaddedRowSize = width;
  86041. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86042. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86043. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86044. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86045. }
  86046. else {
  86047. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86048. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86049. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86050. }
  86051. }
  86052. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86053. width *= 0.5;
  86054. height *= 0.5;
  86055. width = Math.max(1.0, width);
  86056. height = Math.max(1.0, height);
  86057. }
  86058. if (currentFace !== undefined) {
  86059. // Loading a single face
  86060. break;
  86061. }
  86062. }
  86063. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86064. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86065. size: header[off_width],
  86066. right: sphericalPolynomialFaces[0],
  86067. left: sphericalPolynomialFaces[1],
  86068. up: sphericalPolynomialFaces[2],
  86069. down: sphericalPolynomialFaces[3],
  86070. front: sphericalPolynomialFaces[4],
  86071. back: sphericalPolynomialFaces[5],
  86072. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86073. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86074. gammaSpace: false,
  86075. });
  86076. }
  86077. else {
  86078. info.sphericalPolynomial = undefined;
  86079. }
  86080. };
  86081. DDSTools.StoreLODInAlphaChannel = false;
  86082. return DDSTools;
  86083. }());
  86084. BABYLON.DDSTools = DDSTools;
  86085. })(BABYLON || (BABYLON = {}));
  86086. //# sourceMappingURL=babylon.dds.js.map
  86087. var BABYLON;
  86088. (function (BABYLON) {
  86089. /**
  86090. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86091. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86092. */
  86093. var KhronosTextureContainer = /** @class */ (function () {
  86094. /**
  86095. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86096. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86097. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86098. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86099. */
  86100. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86101. this.arrayBuffer = arrayBuffer;
  86102. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86103. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86104. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86105. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86106. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86107. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86108. BABYLON.Tools.Error("texture missing KTX identifier");
  86109. return;
  86110. }
  86111. // load the reset of the header in native 32 bit int
  86112. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86113. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86114. var oppositeEndianess = header[0] === 0x01020304;
  86115. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86116. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86117. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86118. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86119. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86120. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86121. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86122. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86123. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86124. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86125. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86126. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86127. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86128. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86129. if (this.glType !== 0) {
  86130. BABYLON.Tools.Error("only compressed formats currently supported");
  86131. return;
  86132. }
  86133. else {
  86134. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86135. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86136. }
  86137. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86138. BABYLON.Tools.Error("only 2D textures currently supported");
  86139. return;
  86140. }
  86141. if (this.numberOfArrayElements !== 0) {
  86142. BABYLON.Tools.Error("texture arrays not currently supported");
  86143. return;
  86144. }
  86145. if (this.numberOfFaces !== facesExpected) {
  86146. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86147. return;
  86148. }
  86149. // we now have a completely validated file, so could use existence of loadType as success
  86150. // would need to make this more elaborate & adjust checks above to support more than one load type
  86151. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86152. }
  86153. // not as fast hardware based, but will probably never need to use
  86154. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86155. return ((val & 0xFF) << 24)
  86156. | ((val & 0xFF00) << 8)
  86157. | ((val >> 8) & 0xFF00)
  86158. | ((val >> 24) & 0xFF);
  86159. };
  86160. /**
  86161. * It is assumed that the texture has already been created & is currently bound
  86162. */
  86163. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86164. switch (this.loadType) {
  86165. case KhronosTextureContainer.COMPRESSED_2D:
  86166. this._upload2DCompressedLevels(gl, loadMipmaps);
  86167. break;
  86168. case KhronosTextureContainer.TEX_2D:
  86169. case KhronosTextureContainer.COMPRESSED_3D:
  86170. case KhronosTextureContainer.TEX_3D:
  86171. }
  86172. };
  86173. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86174. // initialize width & height for level 1
  86175. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86176. var width = this.pixelWidth;
  86177. var height = this.pixelHeight;
  86178. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86179. for (var level = 0; level < mipmapCount; level++) {
  86180. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86181. for (var face = 0; face < this.numberOfFaces; face++) {
  86182. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86183. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86184. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86185. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86186. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86187. }
  86188. width = Math.max(1.0, width * 0.5);
  86189. height = Math.max(1.0, height * 0.5);
  86190. }
  86191. };
  86192. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86193. // load types
  86194. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86195. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86196. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86197. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86198. return KhronosTextureContainer;
  86199. }());
  86200. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86201. })(BABYLON || (BABYLON = {}));
  86202. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86203. var BABYLON;
  86204. (function (BABYLON) {
  86205. var Debug;
  86206. (function (Debug) {
  86207. /**
  86208. * Class used to render a debug view of a given skeleton
  86209. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86210. */
  86211. var SkeletonViewer = /** @class */ (function () {
  86212. /**
  86213. * Creates a new SkeletonViewer
  86214. * @param skeleton defines the skeleton to render
  86215. * @param mesh defines the mesh attached to the skeleton
  86216. * @param scene defines the hosting scene
  86217. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86218. * @param renderingGroupId defines the rendering group id to use with the viewer
  86219. */
  86220. function SkeletonViewer(
  86221. /** defines the skeleton to render */
  86222. skeleton,
  86223. /** defines the mesh attached to the skeleton */
  86224. mesh, scene,
  86225. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86226. autoUpdateBonesMatrices,
  86227. /** defines the rendering group id to use with the viewer */
  86228. renderingGroupId) {
  86229. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86230. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86231. this.skeleton = skeleton;
  86232. this.mesh = mesh;
  86233. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86234. this.renderingGroupId = renderingGroupId;
  86235. /** Gets or sets the color used to render the skeleton */
  86236. this.color = BABYLON.Color3.White();
  86237. this._debugLines = new Array();
  86238. this._isEnabled = false;
  86239. this._scene = scene;
  86240. this.update();
  86241. this._renderFunction = this.update.bind(this);
  86242. }
  86243. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86244. get: function () {
  86245. return this._isEnabled;
  86246. },
  86247. /** Gets or sets a boolean indicating if the viewer is enabled */
  86248. set: function (value) {
  86249. if (this._isEnabled === value) {
  86250. return;
  86251. }
  86252. this._isEnabled = value;
  86253. if (value) {
  86254. this._scene.registerBeforeRender(this._renderFunction);
  86255. }
  86256. else {
  86257. this._scene.unregisterBeforeRender(this._renderFunction);
  86258. }
  86259. },
  86260. enumerable: true,
  86261. configurable: true
  86262. });
  86263. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86264. if (x === void 0) { x = 0; }
  86265. if (y === void 0) { y = 0; }
  86266. if (z === void 0) { z = 0; }
  86267. var tmat = BABYLON.Tmp.Matrix[0];
  86268. var parentBone = bone.getParent();
  86269. tmat.copyFrom(bone.getLocalMatrix());
  86270. if (x !== 0 || y !== 0 || z !== 0) {
  86271. var tmat2 = BABYLON.Tmp.Matrix[1];
  86272. BABYLON.Matrix.IdentityToRef(tmat2);
  86273. tmat2.m[12] = x;
  86274. tmat2.m[13] = y;
  86275. tmat2.m[14] = z;
  86276. tmat2.multiplyToRef(tmat, tmat);
  86277. }
  86278. if (parentBone) {
  86279. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86280. }
  86281. tmat.multiplyToRef(meshMat, tmat);
  86282. position.x = tmat.m[12];
  86283. position.y = tmat.m[13];
  86284. position.z = tmat.m[14];
  86285. };
  86286. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86287. var len = bones.length;
  86288. var meshPos = this.mesh.position;
  86289. for (var i = 0; i < len; i++) {
  86290. var bone = bones[i];
  86291. var points = this._debugLines[i];
  86292. if (!points) {
  86293. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86294. this._debugLines[i] = points;
  86295. }
  86296. this._getBonePosition(points[0], bone, meshMat);
  86297. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86298. points[0].subtractInPlace(meshPos);
  86299. points[1].subtractInPlace(meshPos);
  86300. }
  86301. };
  86302. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86303. var len = bones.length;
  86304. var boneNum = 0;
  86305. var meshPos = this.mesh.position;
  86306. for (var i = len - 1; i >= 0; i--) {
  86307. var childBone = bones[i];
  86308. var parentBone = childBone.getParent();
  86309. if (!parentBone) {
  86310. continue;
  86311. }
  86312. var points = this._debugLines[boneNum];
  86313. if (!points) {
  86314. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86315. this._debugLines[boneNum] = points;
  86316. }
  86317. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86318. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86319. points[0].subtractInPlace(meshPos);
  86320. points[1].subtractInPlace(meshPos);
  86321. boneNum++;
  86322. }
  86323. };
  86324. /** Update the viewer to sync with current skeleton state */
  86325. SkeletonViewer.prototype.update = function () {
  86326. if (this.autoUpdateBonesMatrices) {
  86327. this.skeleton.computeAbsoluteTransforms();
  86328. }
  86329. if (this.skeleton.bones[0].length === undefined) {
  86330. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86331. }
  86332. else {
  86333. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86334. }
  86335. if (!this._debugMesh) {
  86336. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86337. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86338. }
  86339. else {
  86340. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86341. }
  86342. this._debugMesh.position.copyFrom(this.mesh.position);
  86343. this._debugMesh.color = this.color;
  86344. };
  86345. /** Release associated resources */
  86346. SkeletonViewer.prototype.dispose = function () {
  86347. if (this._debugMesh) {
  86348. this.isEnabled = false;
  86349. this._debugMesh.dispose();
  86350. this._debugMesh = null;
  86351. }
  86352. };
  86353. return SkeletonViewer;
  86354. }());
  86355. Debug.SkeletonViewer = SkeletonViewer;
  86356. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86357. })(BABYLON || (BABYLON = {}));
  86358. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86359. /**
  86360. * Module Debug contains the (visual) components to debug a scene correctly
  86361. */
  86362. var BABYLON;
  86363. (function (BABYLON) {
  86364. var Debug;
  86365. (function (Debug) {
  86366. /**
  86367. * The Axes viewer will show 3 axes in a specific point in space
  86368. */
  86369. var AxesViewer = /** @class */ (function () {
  86370. /**
  86371. * Creates a new AxesViewer
  86372. * @param scene defines the hosting scene
  86373. * @param scaleLines defines a number used to scale line length (1 by default)
  86374. */
  86375. function AxesViewer(scene, scaleLines) {
  86376. if (scaleLines === void 0) { scaleLines = 1; }
  86377. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86378. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86379. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86380. /**
  86381. * Gets or sets a number used to scale line length
  86382. */
  86383. this.scaleLines = 1;
  86384. this.scaleLines = scaleLines;
  86385. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86386. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86387. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86388. this._xmesh.renderingGroupId = 2;
  86389. this._ymesh.renderingGroupId = 2;
  86390. this._zmesh.renderingGroupId = 2;
  86391. this._xmesh.material.checkReadyOnlyOnce = true;
  86392. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86393. this._ymesh.material.checkReadyOnlyOnce = true;
  86394. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86395. this._zmesh.material.checkReadyOnlyOnce = true;
  86396. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86397. this.scene = scene;
  86398. }
  86399. /**
  86400. * Force the viewer to update
  86401. * @param position defines the position of the viewer
  86402. * @param xaxis defines the x axis of the viewer
  86403. * @param yaxis defines the y axis of the viewer
  86404. * @param zaxis defines the z axis of the viewer
  86405. */
  86406. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86407. var scaleLines = this.scaleLines;
  86408. if (this._xmesh) {
  86409. this._xmesh.position.copyFrom(position);
  86410. }
  86411. if (this._ymesh) {
  86412. this._ymesh.position.copyFrom(position);
  86413. }
  86414. if (this._zmesh) {
  86415. this._zmesh.position.copyFrom(position);
  86416. }
  86417. var point2 = this._xline[1];
  86418. point2.x = xaxis.x * scaleLines;
  86419. point2.y = xaxis.y * scaleLines;
  86420. point2.z = xaxis.z * scaleLines;
  86421. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86422. point2 = this._yline[1];
  86423. point2.x = yaxis.x * scaleLines;
  86424. point2.y = yaxis.y * scaleLines;
  86425. point2.z = yaxis.z * scaleLines;
  86426. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86427. point2 = this._zline[1];
  86428. point2.x = zaxis.x * scaleLines;
  86429. point2.y = zaxis.y * scaleLines;
  86430. point2.z = zaxis.z * scaleLines;
  86431. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86432. };
  86433. /** Releases resources */
  86434. AxesViewer.prototype.dispose = function () {
  86435. if (this._xmesh) {
  86436. this._xmesh.dispose();
  86437. }
  86438. if (this._ymesh) {
  86439. this._ymesh.dispose();
  86440. }
  86441. if (this._zmesh) {
  86442. this._zmesh.dispose();
  86443. }
  86444. this._xmesh = null;
  86445. this._ymesh = null;
  86446. this._zmesh = null;
  86447. this.scene = null;
  86448. };
  86449. return AxesViewer;
  86450. }());
  86451. Debug.AxesViewer = AxesViewer;
  86452. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86453. })(BABYLON || (BABYLON = {}));
  86454. //# sourceMappingURL=babylon.axesViewer.js.map
  86455. var BABYLON;
  86456. (function (BABYLON) {
  86457. var Debug;
  86458. (function (Debug) {
  86459. /**
  86460. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86461. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86462. */
  86463. var BoneAxesViewer = /** @class */ (function (_super) {
  86464. __extends(BoneAxesViewer, _super);
  86465. /**
  86466. * Creates a new BoneAxesViewer
  86467. * @param scene defines the hosting scene
  86468. * @param bone defines the target bone
  86469. * @param mesh defines the target mesh
  86470. * @param scaleLines defines a scaling factor for line length (1 by default)
  86471. */
  86472. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86473. if (scaleLines === void 0) { scaleLines = 1; }
  86474. var _this = _super.call(this, scene, scaleLines) || this;
  86475. /** Gets current position */
  86476. _this.pos = BABYLON.Vector3.Zero();
  86477. /** Gets direction of X axis */
  86478. _this.xaxis = BABYLON.Vector3.Zero();
  86479. /** Gets direction of Y axis */
  86480. _this.yaxis = BABYLON.Vector3.Zero();
  86481. /** Gets direction of Z axis */
  86482. _this.zaxis = BABYLON.Vector3.Zero();
  86483. _this.mesh = mesh;
  86484. _this.bone = bone;
  86485. return _this;
  86486. }
  86487. /**
  86488. * Force the viewer to update
  86489. */
  86490. BoneAxesViewer.prototype.update = function () {
  86491. if (!this.mesh || !this.bone) {
  86492. return;
  86493. }
  86494. var bone = this.bone;
  86495. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86496. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86497. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86498. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86499. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86500. };
  86501. /** Releases resources */
  86502. BoneAxesViewer.prototype.dispose = function () {
  86503. if (this.mesh) {
  86504. this.mesh = null;
  86505. this.bone = null;
  86506. _super.prototype.dispose.call(this);
  86507. }
  86508. };
  86509. return BoneAxesViewer;
  86510. }(Debug.AxesViewer));
  86511. Debug.BoneAxesViewer = BoneAxesViewer;
  86512. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86513. })(BABYLON || (BABYLON = {}));
  86514. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86515. var BABYLON;
  86516. (function (BABYLON) {
  86517. var RayHelper = /** @class */ (function () {
  86518. function RayHelper(ray) {
  86519. this.ray = ray;
  86520. }
  86521. RayHelper.CreateAndShow = function (ray, scene, color) {
  86522. var helper = new RayHelper(ray);
  86523. helper.show(scene, color);
  86524. return helper;
  86525. };
  86526. RayHelper.prototype.show = function (scene, color) {
  86527. if (!this._renderFunction && this.ray) {
  86528. var ray = this.ray;
  86529. this._renderFunction = this._render.bind(this);
  86530. this._scene = scene;
  86531. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86532. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86533. if (this._renderFunction) {
  86534. this._scene.registerBeforeRender(this._renderFunction);
  86535. }
  86536. }
  86537. if (color && this._renderLine) {
  86538. this._renderLine.color.copyFrom(color);
  86539. }
  86540. };
  86541. RayHelper.prototype.hide = function () {
  86542. if (this._renderFunction && this._scene) {
  86543. this._scene.unregisterBeforeRender(this._renderFunction);
  86544. this._scene = null;
  86545. this._renderFunction = null;
  86546. if (this._renderLine) {
  86547. this._renderLine.dispose();
  86548. this._renderLine = null;
  86549. }
  86550. this._renderPoints = [];
  86551. }
  86552. };
  86553. RayHelper.prototype._render = function () {
  86554. var ray = this.ray;
  86555. if (!ray) {
  86556. return;
  86557. }
  86558. var point = this._renderPoints[1];
  86559. var len = Math.min(ray.length, 1000000);
  86560. point.copyFrom(ray.direction);
  86561. point.scaleInPlace(len);
  86562. point.addInPlace(ray.origin);
  86563. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86564. };
  86565. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86566. this._attachedToMesh = mesh;
  86567. var ray = this.ray;
  86568. if (!ray) {
  86569. return;
  86570. }
  86571. if (!ray.direction) {
  86572. ray.direction = BABYLON.Vector3.Zero();
  86573. }
  86574. if (!ray.origin) {
  86575. ray.origin = BABYLON.Vector3.Zero();
  86576. }
  86577. if (length) {
  86578. ray.length = length;
  86579. }
  86580. if (!meshSpaceOrigin) {
  86581. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86582. }
  86583. if (!meshSpaceDirection) {
  86584. // -1 so that this will work with Mesh.lookAt
  86585. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86586. }
  86587. if (!this._meshSpaceDirection) {
  86588. this._meshSpaceDirection = meshSpaceDirection.clone();
  86589. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86590. }
  86591. else {
  86592. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86593. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86594. }
  86595. if (!this._updateToMeshFunction) {
  86596. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86597. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86598. }
  86599. this._updateToMesh();
  86600. };
  86601. RayHelper.prototype.detachFromMesh = function () {
  86602. if (this._attachedToMesh) {
  86603. if (this._updateToMeshFunction) {
  86604. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86605. }
  86606. this._attachedToMesh = null;
  86607. this._updateToMeshFunction = null;
  86608. }
  86609. };
  86610. RayHelper.prototype._updateToMesh = function () {
  86611. var ray = this.ray;
  86612. if (!this._attachedToMesh || !ray) {
  86613. return;
  86614. }
  86615. if (this._attachedToMesh._isDisposed) {
  86616. this.detachFromMesh();
  86617. return;
  86618. }
  86619. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86620. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86621. };
  86622. RayHelper.prototype.dispose = function () {
  86623. this.hide();
  86624. this.detachFromMesh();
  86625. this.ray = null;
  86626. };
  86627. return RayHelper;
  86628. }());
  86629. BABYLON.RayHelper = RayHelper;
  86630. })(BABYLON || (BABYLON = {}));
  86631. //# sourceMappingURL=babylon.rayHelper.js.map
  86632. var BABYLON;
  86633. (function (BABYLON) {
  86634. // load the inspector using require, if not present in the global namespace.
  86635. var DebugLayer = /** @class */ (function () {
  86636. function DebugLayer(scene) {
  86637. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86638. this._scene = scene;
  86639. // load inspector using require, if it doesn't exist on the global namespace.
  86640. }
  86641. /** Creates the inspector window. */
  86642. DebugLayer.prototype._createInspector = function (config) {
  86643. if (config === void 0) { config = {}; }
  86644. var popup = config.popup || false;
  86645. var initialTab = config.initialTab || 0;
  86646. var parentElement = config.parentElement || null;
  86647. if (!this._inspector) {
  86648. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86649. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86650. } // else nothing to do,; instance is already existing
  86651. };
  86652. DebugLayer.prototype.isVisible = function () {
  86653. if (!this._inspector) {
  86654. return false;
  86655. }
  86656. return true;
  86657. };
  86658. DebugLayer.prototype.hide = function () {
  86659. if (this._inspector) {
  86660. try {
  86661. this._inspector.dispose();
  86662. }
  86663. catch (e) {
  86664. // If the inspector has been removed directly from the inspector tool
  86665. }
  86666. this._inspector = null;
  86667. }
  86668. };
  86669. /**
  86670. *
  86671. * Launch the debugLayer.
  86672. *
  86673. * initialTab:
  86674. * | Value | Tab Name |
  86675. * | --- | --- |
  86676. * | 0 | Scene |
  86677. * | 1 | Console |
  86678. * | 2 | Stats |
  86679. * | 3 | Textures |
  86680. * | 4 | Mesh |
  86681. * | 5 | Light |
  86682. * | 6 | Material |
  86683. * | 7 | GLTF |
  86684. * | 8 | GUI |
  86685. * | 9 | Physics |
  86686. * | 10 | Camera |
  86687. * | 11 | Audio |
  86688. *
  86689. */
  86690. DebugLayer.prototype.show = function (config) {
  86691. if (config === void 0) { config = {}; }
  86692. if (typeof this.BJSINSPECTOR == 'undefined') {
  86693. // Load inspector and add it to the DOM
  86694. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86695. }
  86696. else {
  86697. // Otherwise creates the inspector
  86698. this._createInspector(config);
  86699. }
  86700. };
  86701. /**
  86702. * Gets the active tab
  86703. * @return the index of the active tab or -1 if the inspector is hidden
  86704. */
  86705. DebugLayer.prototype.getActiveTab = function () {
  86706. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86707. };
  86708. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86709. return DebugLayer;
  86710. }());
  86711. BABYLON.DebugLayer = DebugLayer;
  86712. })(BABYLON || (BABYLON = {}));
  86713. //# sourceMappingURL=babylon.debugLayer.js.map
  86714. var BABYLON;
  86715. (function (BABYLON) {
  86716. var Debug;
  86717. (function (Debug) {
  86718. /**
  86719. * Used to show the physics impostor around the specific mesh
  86720. */
  86721. var PhysicsViewer = /** @class */ (function () {
  86722. /**
  86723. * Creates a new PhysicsViewer
  86724. * @param scene defines the hosting scene
  86725. */
  86726. function PhysicsViewer(scene) {
  86727. /** @hidden */
  86728. this._impostors = [];
  86729. /** @hidden */
  86730. this._meshes = [];
  86731. /** @hidden */
  86732. this._numMeshes = 0;
  86733. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86734. var physicEngine = this._scene.getPhysicsEngine();
  86735. if (physicEngine) {
  86736. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86737. }
  86738. }
  86739. /** @hidden */
  86740. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86741. var plugin = this._physicsEnginePlugin;
  86742. for (var i = 0; i < this._numMeshes; i++) {
  86743. var impostor = this._impostors[i];
  86744. if (!impostor) {
  86745. continue;
  86746. }
  86747. if (impostor.isDisposed) {
  86748. this.hideImpostor(this._impostors[i--]);
  86749. }
  86750. else {
  86751. var mesh = this._meshes[i];
  86752. if (mesh && plugin) {
  86753. plugin.syncMeshWithImpostor(mesh, impostor);
  86754. }
  86755. }
  86756. }
  86757. };
  86758. /**
  86759. * Renders a specified physic impostor
  86760. * @param impostor defines the impostor to render
  86761. */
  86762. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86763. if (!this._scene) {
  86764. return;
  86765. }
  86766. for (var i = 0; i < this._numMeshes; i++) {
  86767. if (this._impostors[i] == impostor) {
  86768. return;
  86769. }
  86770. }
  86771. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86772. if (debugMesh) {
  86773. this._impostors[this._numMeshes] = impostor;
  86774. this._meshes[this._numMeshes] = debugMesh;
  86775. if (this._numMeshes === 0) {
  86776. this._renderFunction = this._updateDebugMeshes.bind(this);
  86777. this._scene.registerBeforeRender(this._renderFunction);
  86778. }
  86779. this._numMeshes++;
  86780. }
  86781. };
  86782. /**
  86783. * Hides a specified physic impostor
  86784. * @param impostor defines the impostor to hide
  86785. */
  86786. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86787. if (!impostor || !this._scene) {
  86788. return;
  86789. }
  86790. var removed = false;
  86791. for (var i = 0; i < this._numMeshes; i++) {
  86792. if (this._impostors[i] == impostor) {
  86793. var mesh = this._meshes[i];
  86794. if (!mesh) {
  86795. continue;
  86796. }
  86797. this._scene.removeMesh(mesh);
  86798. mesh.dispose();
  86799. this._numMeshes--;
  86800. if (this._numMeshes > 0) {
  86801. this._meshes[i] = this._meshes[this._numMeshes];
  86802. this._impostors[i] = this._impostors[this._numMeshes];
  86803. this._meshes[this._numMeshes] = null;
  86804. this._impostors[this._numMeshes] = null;
  86805. }
  86806. else {
  86807. this._meshes[0] = null;
  86808. this._impostors[0] = null;
  86809. }
  86810. removed = true;
  86811. break;
  86812. }
  86813. }
  86814. if (removed && this._numMeshes === 0) {
  86815. this._scene.unregisterBeforeRender(this._renderFunction);
  86816. }
  86817. };
  86818. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86819. if (!this._debugMaterial) {
  86820. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86821. this._debugMaterial.wireframe = true;
  86822. }
  86823. return this._debugMaterial;
  86824. };
  86825. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86826. if (!this._debugBoxMesh) {
  86827. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86828. this._debugBoxMesh.renderingGroupId = 1;
  86829. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86830. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86831. scene.removeMesh(this._debugBoxMesh);
  86832. }
  86833. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86834. };
  86835. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86836. if (!this._debugSphereMesh) {
  86837. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86838. this._debugSphereMesh.renderingGroupId = 1;
  86839. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86840. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86841. scene.removeMesh(this._debugSphereMesh);
  86842. }
  86843. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86844. };
  86845. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86846. var mesh = null;
  86847. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86848. mesh = this._getDebugBoxMesh(scene);
  86849. impostor.getBoxSizeToRef(mesh.scaling);
  86850. }
  86851. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86852. mesh = this._getDebugSphereMesh(scene);
  86853. var radius = impostor.getRadius();
  86854. mesh.scaling.x = radius * 2;
  86855. mesh.scaling.y = radius * 2;
  86856. mesh.scaling.z = radius * 2;
  86857. }
  86858. return mesh;
  86859. };
  86860. /** Releases all resources */
  86861. PhysicsViewer.prototype.dispose = function () {
  86862. for (var i = 0; i < this._numMeshes; i++) {
  86863. this.hideImpostor(this._impostors[i]);
  86864. }
  86865. if (this._debugBoxMesh) {
  86866. this._debugBoxMesh.dispose();
  86867. }
  86868. if (this._debugSphereMesh) {
  86869. this._debugSphereMesh.dispose();
  86870. }
  86871. if (this._debugMaterial) {
  86872. this._debugMaterial.dispose();
  86873. }
  86874. this._impostors.length = 0;
  86875. this._scene = null;
  86876. this._physicsEnginePlugin = null;
  86877. };
  86878. return PhysicsViewer;
  86879. }());
  86880. Debug.PhysicsViewer = PhysicsViewer;
  86881. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86882. })(BABYLON || (BABYLON = {}));
  86883. //# sourceMappingURL=babylon.physicsViewer.js.map
  86884. var BABYLON;
  86885. (function (BABYLON) {
  86886. var BoundingBoxRenderer = /** @class */ (function () {
  86887. function BoundingBoxRenderer(scene) {
  86888. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86889. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86890. this.showBackLines = true;
  86891. this.renderList = new BABYLON.SmartArray(32);
  86892. this._vertexBuffers = {};
  86893. this._scene = scene;
  86894. }
  86895. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86896. if (this._colorShader) {
  86897. return;
  86898. }
  86899. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86900. attributes: [BABYLON.VertexBuffer.PositionKind],
  86901. uniforms: ["world", "viewProjection", "color"]
  86902. });
  86903. var engine = this._scene.getEngine();
  86904. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86905. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86906. this._createIndexBuffer();
  86907. };
  86908. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86909. var engine = this._scene.getEngine();
  86910. 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]);
  86911. };
  86912. BoundingBoxRenderer.prototype._rebuild = function () {
  86913. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86914. if (vb) {
  86915. vb._rebuild();
  86916. }
  86917. this._createIndexBuffer();
  86918. };
  86919. BoundingBoxRenderer.prototype.reset = function () {
  86920. this.renderList.reset();
  86921. };
  86922. BoundingBoxRenderer.prototype.render = function () {
  86923. if (this.renderList.length === 0) {
  86924. return;
  86925. }
  86926. this._prepareRessources();
  86927. if (!this._colorShader.isReady()) {
  86928. return;
  86929. }
  86930. var engine = this._scene.getEngine();
  86931. engine.setDepthWrite(false);
  86932. this._colorShader._preBind();
  86933. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86934. var boundingBox = this.renderList.data[boundingBoxIndex];
  86935. var min = boundingBox.minimum;
  86936. var max = boundingBox.maximum;
  86937. var diff = max.subtract(min);
  86938. var median = min.add(diff.scale(0.5));
  86939. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86940. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86941. .multiply(boundingBox.getWorldMatrix());
  86942. // VBOs
  86943. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86944. if (this.showBackLines) {
  86945. // Back
  86946. engine.setDepthFunctionToGreaterOrEqual();
  86947. this._scene.resetCachedMaterial();
  86948. this._colorShader.setColor4("color", this.backColor.toColor4());
  86949. this._colorShader.bind(worldMatrix);
  86950. // Draw order
  86951. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86952. }
  86953. // Front
  86954. engine.setDepthFunctionToLess();
  86955. this._scene.resetCachedMaterial();
  86956. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86957. this._colorShader.bind(worldMatrix);
  86958. // Draw order
  86959. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86960. }
  86961. this._colorShader.unbind();
  86962. engine.setDepthFunctionToLessOrEqual();
  86963. engine.setDepthWrite(true);
  86964. };
  86965. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86966. this._prepareRessources();
  86967. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86968. return;
  86969. }
  86970. var engine = this._scene.getEngine();
  86971. engine.setDepthWrite(false);
  86972. engine.setColorWrite(false);
  86973. this._colorShader._preBind();
  86974. var boundingBox = mesh._boundingInfo.boundingBox;
  86975. var min = boundingBox.minimum;
  86976. var max = boundingBox.maximum;
  86977. var diff = max.subtract(min);
  86978. var median = min.add(diff.scale(0.5));
  86979. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86980. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86981. .multiply(boundingBox.getWorldMatrix());
  86982. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86983. engine.setDepthFunctionToLess();
  86984. this._scene.resetCachedMaterial();
  86985. this._colorShader.bind(worldMatrix);
  86986. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86987. this._colorShader.unbind();
  86988. engine.setDepthFunctionToLessOrEqual();
  86989. engine.setDepthWrite(true);
  86990. engine.setColorWrite(true);
  86991. };
  86992. BoundingBoxRenderer.prototype.dispose = function () {
  86993. if (!this._colorShader) {
  86994. return;
  86995. }
  86996. this.renderList.dispose();
  86997. this._colorShader.dispose();
  86998. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86999. if (buffer) {
  87000. buffer.dispose();
  87001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87002. }
  87003. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87004. };
  87005. return BoundingBoxRenderer;
  87006. }());
  87007. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87008. })(BABYLON || (BABYLON = {}));
  87009. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87010. var BABYLON;
  87011. (function (BABYLON) {
  87012. /**
  87013. * Renders a layer on top of an existing scene
  87014. */
  87015. var UtilityLayerRenderer = /** @class */ (function () {
  87016. /**
  87017. * Instantiates a UtilityLayerRenderer
  87018. * @param originalScene the original scene that will be rendered on top of
  87019. */
  87020. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87021. var _this = this;
  87022. this.originalScene = originalScene;
  87023. this._pointerCaptures = {};
  87024. this._lastPointerEvents = {};
  87025. /**
  87026. * If the utility layer should automatically be rendered on top of existing scene
  87027. */
  87028. this.shouldRender = true;
  87029. /**
  87030. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87031. */
  87032. this.onlyCheckPointerDownEvents = true;
  87033. /**
  87034. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87035. */
  87036. this.processAllEvents = false;
  87037. /**
  87038. * Observable raised when the pointer move from the utility layer scene to the main scene
  87039. */
  87040. this.onPointerOutObservable = new BABYLON.Observable();
  87041. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87042. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87043. originalScene.getEngine().scenes.pop();
  87044. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87045. this.utilityLayerScene.detachControl();
  87046. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87047. if (!_this.processAllEvents) {
  87048. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87049. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87050. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87051. return;
  87052. }
  87053. }
  87054. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87055. if (!prePointerInfo.ray && utilityScenePick) {
  87056. prePointerInfo.ray = utilityScenePick.ray;
  87057. }
  87058. // always fire the prepointer oversvable
  87059. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87060. // allow every non pointer down event to flow to the utility layer
  87061. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87062. if (!prePointerInfo.skipOnPointerObservable) {
  87063. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87064. }
  87065. return;
  87066. }
  87067. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87068. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87069. if (utilityScenePick && utilityScenePick.hit) {
  87070. if (!prePointerInfo.skipOnPointerObservable) {
  87071. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87072. }
  87073. prePointerInfo.skipOnPointerObservable = true;
  87074. }
  87075. }
  87076. else {
  87077. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87078. var pointerEvent = (prePointerInfo.event);
  87079. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87080. if (originalScenePick && utilityScenePick) {
  87081. if (utilityScenePick.distance === 0) {
  87082. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87083. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87084. }
  87085. }
  87086. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87087. if (!prePointerInfo.skipOnPointerObservable) {
  87088. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87089. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87090. }
  87091. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87092. }
  87093. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87094. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87095. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87096. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87097. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87098. }
  87099. }
  87100. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87101. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87102. }
  87103. }
  87104. }
  87105. });
  87106. // Render directly on top of existing scene without clearing
  87107. this.utilityLayerScene.autoClear = false;
  87108. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87109. if (_this.shouldRender) {
  87110. _this.render();
  87111. }
  87112. });
  87113. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87114. _this.dispose();
  87115. });
  87116. this._updateCamera();
  87117. }
  87118. /**
  87119. * Renders the utility layers scene on top of the original scene
  87120. */
  87121. UtilityLayerRenderer.prototype.render = function () {
  87122. this._updateCamera();
  87123. this.utilityLayerScene.render(false);
  87124. };
  87125. /**
  87126. * Disposes of the renderer
  87127. */
  87128. UtilityLayerRenderer.prototype.dispose = function () {
  87129. this.onPointerOutObservable.clear();
  87130. if (this._afterRenderObserver) {
  87131. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87132. }
  87133. if (this._sceneDisposeObserver) {
  87134. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87135. }
  87136. if (this._originalPointerObserver) {
  87137. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87138. }
  87139. this.utilityLayerScene.dispose();
  87140. };
  87141. UtilityLayerRenderer.prototype._updateCamera = function () {
  87142. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87143. };
  87144. return UtilityLayerRenderer;
  87145. }());
  87146. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87147. })(BABYLON || (BABYLON = {}));
  87148. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87149. var BABYLON;
  87150. (function (BABYLON) {
  87151. /**
  87152. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87153. */
  87154. var PointerDragBehavior = /** @class */ (function () {
  87155. /**
  87156. * Creates a pointer drag behavior that can be attached to a mesh
  87157. * @param options The drag axis or normal of the plane that will be dragged across.
  87158. */
  87159. function PointerDragBehavior(options) {
  87160. this.options = options;
  87161. this._draggingID = -1;
  87162. /**
  87163. * Fires each time the attached mesh is dragged with the pointer
  87164. */
  87165. this.onDragObservable = new BABYLON.Observable();
  87166. /**
  87167. * Fires each time a drag begins (eg. mouse down on mesh)
  87168. */
  87169. this.onDragStartObservable = new BABYLON.Observable();
  87170. /**
  87171. * Fires each time a drag ends (eg. mouse release after drag)
  87172. */
  87173. this.onDragEndObservable = new BABYLON.Observable();
  87174. /**
  87175. * If the attached mesh should be moved when dragged
  87176. */
  87177. this.moveAttached = true;
  87178. /**
  87179. * Mesh with the position where the drag plane should be placed
  87180. */
  87181. this._dragPlaneParent = null;
  87182. /**
  87183. * If the drag behavior will react to drag events
  87184. */
  87185. this.enabled = true;
  87186. var optionCount = 0;
  87187. if (options.dragAxis) {
  87188. optionCount++;
  87189. }
  87190. if (options.dragPlaneNormal) {
  87191. optionCount++;
  87192. }
  87193. if (optionCount > 1) {
  87194. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87195. }
  87196. if (optionCount < 1) {
  87197. throw "At least one drag mode option must be specified";
  87198. }
  87199. }
  87200. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87201. /**
  87202. * The name of the behavior
  87203. */
  87204. get: function () {
  87205. return "PointerDrag";
  87206. },
  87207. enumerable: true,
  87208. configurable: true
  87209. });
  87210. /**
  87211. * Initializes the behavior
  87212. */
  87213. PointerDragBehavior.prototype.init = function () { };
  87214. /**
  87215. * Attaches the drag behavior the passed in mesh
  87216. * @param ownerNode The mesh that will be dragged around once attached
  87217. */
  87218. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87219. var _this = this;
  87220. this._scene = ownerNode.getScene();
  87221. this._attachedNode = ownerNode;
  87222. // Initialize drag plane to not interfere with existing scene
  87223. if (!PointerDragBehavior._planeScene) {
  87224. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87225. this._scene.getEngine().scenes.pop();
  87226. }
  87227. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87228. // State of the drag
  87229. var dragging = false;
  87230. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87231. var delta = new BABYLON.Vector3(0, 0, 0);
  87232. var pickPredicate = function (m) {
  87233. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87234. };
  87235. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87236. if (!_this.enabled) {
  87237. return;
  87238. }
  87239. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87240. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87241. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87242. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87243. if (pickedPoint) {
  87244. dragging = true;
  87245. _this._draggingID = pointerInfo.event.pointerId;
  87246. lastPosition.copyFrom(pickedPoint);
  87247. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87248. }
  87249. }
  87250. }
  87251. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87252. if (_this._draggingID == pointerInfo.event.pointerId) {
  87253. dragging = false;
  87254. _this._draggingID = -1;
  87255. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87256. }
  87257. }
  87258. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87259. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87260. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87261. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87262. if (pickedPoint) {
  87263. // depending on the drag mode option drag accordingly
  87264. if (_this.options.dragAxis) {
  87265. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87266. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87267. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87268. }
  87269. else {
  87270. pickedPoint.subtractToRef(lastPosition, delta);
  87271. }
  87272. if (_this.moveAttached) {
  87273. _this._attachedNode.position.addInPlace(delta);
  87274. }
  87275. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87276. lastPosition.copyFrom(pickedPoint);
  87277. }
  87278. }
  87279. }
  87280. });
  87281. };
  87282. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87283. var _this = this;
  87284. if (!ray) {
  87285. return null;
  87286. }
  87287. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87288. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87289. return pickResult.pickedPoint;
  87290. }
  87291. else {
  87292. return null;
  87293. }
  87294. };
  87295. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87296. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87297. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87298. if (this.options.dragAxis) {
  87299. var camPos = ray.origin;
  87300. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87301. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87302. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87303. // Get perpendicular line from direction to camera and drag axis
  87304. var lineA = pointB.subtract(pointA);
  87305. var lineB = pointC.subtract(pointA);
  87306. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87307. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87308. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87309. this._dragPlane.position.copyFrom(pointA);
  87310. this._dragPlane.lookAt(pointA.add(norm));
  87311. }
  87312. else if (this.options.dragPlaneNormal) {
  87313. this._dragPlane.position.copyFrom(pointA);
  87314. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87315. }
  87316. this._dragPlane.computeWorldMatrix(true);
  87317. };
  87318. /**
  87319. * Detaches the behavior from the mesh
  87320. */
  87321. PointerDragBehavior.prototype.detach = function () {
  87322. if (this._pointerObserver) {
  87323. this._scene.onPointerObservable.remove(this._pointerObserver);
  87324. }
  87325. };
  87326. return PointerDragBehavior;
  87327. }());
  87328. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87329. })(BABYLON || (BABYLON = {}));
  87330. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87331. var BABYLON;
  87332. (function (BABYLON) {
  87333. /**
  87334. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87335. */
  87336. var Gizmo = /** @class */ (function () {
  87337. /**
  87338. * Creates a gizmo
  87339. * @param gizmoLayer The utility layer the gizmo will be added to
  87340. */
  87341. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87342. var _this = this;
  87343. this.gizmoLayer = gizmoLayer;
  87344. this._interactionsEnabled = true;
  87345. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87346. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87347. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87348. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87349. _this._rootMesh.scaling.set(dist, dist, dist);
  87350. }
  87351. if (_this.attachedMesh) {
  87352. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87353. }
  87354. });
  87355. }
  87356. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87357. };
  87358. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87359. get: function () {
  87360. return this._interactionsEnabled;
  87361. },
  87362. /**
  87363. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87364. */
  87365. set: function (value) {
  87366. this._interactionsEnabled = value;
  87367. this._onInteractionsEnabledChanged(value);
  87368. },
  87369. enumerable: true,
  87370. configurable: true
  87371. });
  87372. /**
  87373. * Disposes of the gizmo
  87374. */
  87375. Gizmo.prototype.dispose = function () {
  87376. this._rootMesh.dispose();
  87377. if (this._beforeRenderObserver) {
  87378. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87379. }
  87380. };
  87381. return Gizmo;
  87382. }());
  87383. BABYLON.Gizmo = Gizmo;
  87384. })(BABYLON || (BABYLON = {}));
  87385. //# sourceMappingURL=babylon.gizmo.js.map
  87386. var BABYLON;
  87387. (function (BABYLON) {
  87388. /**
  87389. * Single axis drag gizmo
  87390. */
  87391. var AxisDragGizmo = /** @class */ (function (_super) {
  87392. __extends(AxisDragGizmo, _super);
  87393. /**
  87394. * Creates an AxisDragGizmo
  87395. * @param gizmoLayer The utility layer the gizmo will be added to
  87396. * @param dragAxis The axis which the gizmo will be able to drag on
  87397. * @param color The color of the gizmo
  87398. */
  87399. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87400. var _this = _super.call(this, gizmoLayer) || this;
  87401. // Create Material
  87402. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87403. coloredMaterial.disableLighting = true;
  87404. coloredMaterial.emissiveColor = color;
  87405. // Build mesh on root node
  87406. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87407. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87408. _this._rootMesh.addChild(arrowMesh);
  87409. _this._rootMesh.addChild(arrowTail);
  87410. // Position arrow pointing in its drag axis
  87411. arrowMesh.scaling.scaleInPlace(0.1);
  87412. arrowMesh.material = coloredMaterial;
  87413. arrowMesh.rotation.x = Math.PI / 2;
  87414. arrowMesh.position.z += 0.3;
  87415. arrowTail.rotation.x = Math.PI / 2;
  87416. arrowTail.material = coloredMaterial;
  87417. arrowTail.position.z += 0.2;
  87418. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87419. // Add drag behavior to handle events when the gizmo is dragged
  87420. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87421. _this._dragBehavior.moveAttached = false;
  87422. _this._rootMesh.addBehavior(_this._dragBehavior);
  87423. _this._dragBehavior.onDragObservable.add(function (event) {
  87424. if (!_this.interactionsEnabled) {
  87425. return;
  87426. }
  87427. if (_this.attachedMesh) {
  87428. _this.attachedMesh.position.addInPlace(event.delta);
  87429. }
  87430. });
  87431. return _this;
  87432. }
  87433. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87434. this._dragBehavior.enabled = value;
  87435. };
  87436. /**
  87437. * Disposes of the gizmo
  87438. */
  87439. AxisDragGizmo.prototype.dispose = function () {
  87440. this._dragBehavior.detach();
  87441. _super.prototype.dispose.call(this);
  87442. };
  87443. return AxisDragGizmo;
  87444. }(BABYLON.Gizmo));
  87445. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87446. })(BABYLON || (BABYLON = {}));
  87447. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87448. var BABYLON;
  87449. (function (BABYLON) {
  87450. /**
  87451. * Single axis scale gizmo
  87452. */
  87453. var AxisScaleGizmo = /** @class */ (function (_super) {
  87454. __extends(AxisScaleGizmo, _super);
  87455. /**
  87456. * Creates an AxisScaleGizmo
  87457. * @param gizmoLayer The utility layer the gizmo will be added to
  87458. * @param dragAxis The axis which the gizmo will be able to scale on
  87459. * @param color The color of the gizmo
  87460. */
  87461. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87462. var _this = _super.call(this, gizmoLayer) || this;
  87463. // Create Material
  87464. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87465. coloredMaterial.disableLighting = true;
  87466. coloredMaterial.emissiveColor = color;
  87467. // Build mesh on root node
  87468. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87469. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87470. _this._rootMesh.addChild(arrowMesh);
  87471. _this._rootMesh.addChild(arrowTail);
  87472. // Position arrow pointing in its drag axis
  87473. arrowMesh.scaling.scaleInPlace(0.1);
  87474. arrowMesh.material = coloredMaterial;
  87475. arrowMesh.rotation.x = Math.PI / 2;
  87476. arrowMesh.position.z += 0.3;
  87477. arrowTail.rotation.x = Math.PI / 2;
  87478. arrowTail.material = coloredMaterial;
  87479. arrowTail.position.z += 0.2;
  87480. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87481. // Add drag behavior to handle events when the gizmo is dragged
  87482. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87483. _this._dragBehavior.moveAttached = false;
  87484. _this._rootMesh.addBehavior(_this._dragBehavior);
  87485. _this._dragBehavior.onDragObservable.add(function (event) {
  87486. if (!_this.interactionsEnabled) {
  87487. return;
  87488. }
  87489. if (_this.attachedMesh) {
  87490. _this.attachedMesh.scaling.addInPlace(event.delta);
  87491. }
  87492. });
  87493. return _this;
  87494. }
  87495. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87496. this._dragBehavior.enabled = value;
  87497. };
  87498. /**
  87499. * Disposes of the gizmo
  87500. */
  87501. AxisScaleGizmo.prototype.dispose = function () {
  87502. this._dragBehavior.detach();
  87503. _super.prototype.dispose.call(this);
  87504. };
  87505. return AxisScaleGizmo;
  87506. }(BABYLON.Gizmo));
  87507. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87508. })(BABYLON || (BABYLON = {}));
  87509. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87510. var BABYLON;
  87511. (function (BABYLON) {
  87512. /**
  87513. * Single plane rotation gizmo
  87514. */
  87515. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87516. __extends(PlaneRotationGizmo, _super);
  87517. /**
  87518. * Creates a PlaneRotationGizmo
  87519. * @param gizmoLayer The utility layer the gizmo will be added to
  87520. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87521. * @param color The color of the gizmo
  87522. */
  87523. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87524. var _this = _super.call(this, gizmoLayer) || this;
  87525. // Create Material
  87526. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87527. coloredMaterial.disableLighting = true;
  87528. coloredMaterial.emissiveColor = color;
  87529. // Build mesh on root node
  87530. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87531. _this._rootMesh.addChild(rotationMesh);
  87532. // Position arrow pointing in its drag axis
  87533. rotationMesh.scaling.scaleInPlace(0.1);
  87534. rotationMesh.material = coloredMaterial;
  87535. rotationMesh.rotation.x = Math.PI / 2;
  87536. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87537. // Add drag behavior to handle events when the gizmo is dragged
  87538. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87539. _this._dragBehavior.moveAttached = false;
  87540. _this._rootMesh.addBehavior(_this._dragBehavior);
  87541. var lastDragPosition = null;
  87542. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87543. if (!_this.interactionsEnabled) {
  87544. return;
  87545. }
  87546. lastDragPosition = e.dragPlanePoint;
  87547. });
  87548. _this._dragBehavior.onDragObservable.add(function (event) {
  87549. if (!_this.interactionsEnabled) {
  87550. return;
  87551. }
  87552. if (_this.attachedMesh && lastDragPosition) {
  87553. if (!_this.attachedMesh.rotationQuaternion) {
  87554. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87555. }
  87556. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87557. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87558. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87559. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87560. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87561. var angle = Math.atan2(cross.length(), dot);
  87562. var up = planeNormal.clone();
  87563. // Flip up vector depending on which side the camera is on
  87564. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87565. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87566. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87567. up.scaleInPlace(-1);
  87568. }
  87569. }
  87570. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87571. if (halfCircleSide)
  87572. angle = -angle;
  87573. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87574. var quaternionCoefficient = Math.sin(angle / 2);
  87575. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87576. // Rotate selected mesh quaternion over fixed axis
  87577. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87578. lastDragPosition = event.dragPlanePoint;
  87579. }
  87580. });
  87581. return _this;
  87582. }
  87583. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87584. this._dragBehavior.enabled = value;
  87585. };
  87586. /**
  87587. * Disposes of the gizmo
  87588. */
  87589. PlaneRotationGizmo.prototype.dispose = function () {
  87590. this._dragBehavior.detach();
  87591. _super.prototype.dispose.call(this);
  87592. };
  87593. return PlaneRotationGizmo;
  87594. }(BABYLON.Gizmo));
  87595. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87596. })(BABYLON || (BABYLON = {}));
  87597. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87598. var BABYLON;
  87599. (function (BABYLON) {
  87600. /**
  87601. * Gizmo that enables dragging a mesh along 3 axis
  87602. */
  87603. var PositionGizmo = /** @class */ (function (_super) {
  87604. __extends(PositionGizmo, _super);
  87605. /**
  87606. * Creates a PositionGizmo
  87607. * @param gizmoLayer The utility layer the gizmo will be added to
  87608. */
  87609. function PositionGizmo(gizmoLayer) {
  87610. var _this = _super.call(this, gizmoLayer) || this;
  87611. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87612. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87613. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87614. return _this;
  87615. }
  87616. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87617. set: function (mesh) {
  87618. this._xDrag.attachedMesh = mesh;
  87619. this._yDrag.attachedMesh = mesh;
  87620. this._zDrag.attachedMesh = mesh;
  87621. },
  87622. enumerable: true,
  87623. configurable: true
  87624. });
  87625. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87626. this._xDrag.interactionsEnabled = value;
  87627. this._yDrag.interactionsEnabled = value;
  87628. this._zDrag.interactionsEnabled = value;
  87629. };
  87630. /**
  87631. * Disposes of the gizmo
  87632. */
  87633. PositionGizmo.prototype.dispose = function () {
  87634. this._xDrag.dispose();
  87635. this._yDrag.dispose();
  87636. this._zDrag.dispose();
  87637. };
  87638. return PositionGizmo;
  87639. }(BABYLON.Gizmo));
  87640. BABYLON.PositionGizmo = PositionGizmo;
  87641. })(BABYLON || (BABYLON = {}));
  87642. //# sourceMappingURL=babylon.positionGizmo.js.map
  87643. var BABYLON;
  87644. (function (BABYLON) {
  87645. /**
  87646. * Gizmo that enables rotating a mesh along 3 axis
  87647. */
  87648. var RotationGizmo = /** @class */ (function (_super) {
  87649. __extends(RotationGizmo, _super);
  87650. /**
  87651. * Creates a RotationGizmo
  87652. * @param gizmoLayer The utility layer the gizmo will be added to
  87653. */
  87654. function RotationGizmo(gizmoLayer) {
  87655. var _this = _super.call(this, gizmoLayer) || this;
  87656. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87657. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87658. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87659. return _this;
  87660. }
  87661. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87662. set: function (mesh) {
  87663. this._xDrag.attachedMesh = mesh;
  87664. this._yDrag.attachedMesh = mesh;
  87665. this._zDrag.attachedMesh = mesh;
  87666. },
  87667. enumerable: true,
  87668. configurable: true
  87669. });
  87670. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87671. this._xDrag.interactionsEnabled = value;
  87672. this._yDrag.interactionsEnabled = value;
  87673. this._zDrag.interactionsEnabled = value;
  87674. };
  87675. /**
  87676. * Disposes of the gizmo
  87677. */
  87678. RotationGizmo.prototype.dispose = function () {
  87679. this._xDrag.dispose();
  87680. this._yDrag.dispose();
  87681. this._zDrag.dispose();
  87682. };
  87683. return RotationGizmo;
  87684. }(BABYLON.Gizmo));
  87685. BABYLON.RotationGizmo = RotationGizmo;
  87686. })(BABYLON || (BABYLON = {}));
  87687. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87688. var BABYLON;
  87689. (function (BABYLON) {
  87690. /**
  87691. * Gizmo that enables scaling a mesh along 3 axis
  87692. */
  87693. var ScaleGizmo = /** @class */ (function (_super) {
  87694. __extends(ScaleGizmo, _super);
  87695. /**
  87696. * Creates a ScaleGizmo
  87697. * @param gizmoLayer The utility layer the gizmo will be added to
  87698. */
  87699. function ScaleGizmo(gizmoLayer) {
  87700. var _this = _super.call(this, gizmoLayer) || this;
  87701. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87702. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87703. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87704. return _this;
  87705. }
  87706. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87707. set: function (mesh) {
  87708. this._xDrag.attachedMesh = mesh;
  87709. this._yDrag.attachedMesh = mesh;
  87710. this._zDrag.attachedMesh = mesh;
  87711. },
  87712. enumerable: true,
  87713. configurable: true
  87714. });
  87715. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87716. this._xDrag.interactionsEnabled = value;
  87717. this._yDrag.interactionsEnabled = value;
  87718. this._zDrag.interactionsEnabled = value;
  87719. };
  87720. /**
  87721. * Disposes of the gizmo
  87722. */
  87723. ScaleGizmo.prototype.dispose = function () {
  87724. this._xDrag.dispose();
  87725. this._yDrag.dispose();
  87726. this._zDrag.dispose();
  87727. };
  87728. return ScaleGizmo;
  87729. }(BABYLON.Gizmo));
  87730. BABYLON.ScaleGizmo = ScaleGizmo;
  87731. })(BABYLON || (BABYLON = {}));
  87732. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87733. var BABYLON;
  87734. (function (BABYLON) {
  87735. /**
  87736. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87737. */
  87738. var GizmoManager = /** @class */ (function () {
  87739. /**
  87740. * Instatiates a gizmo manager
  87741. * @param scene the scene to overlay the gizmos on top of
  87742. * @param options If only a single gizmo should exist at one time
  87743. */
  87744. function GizmoManager(scene, options) {
  87745. var _this = this;
  87746. this.scene = scene;
  87747. // Set of gizmos that are currently in the scene for each mesh
  87748. this._gizmoSet = {};
  87749. this._pointerObserver = null;
  87750. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87751. // Options parsing
  87752. if (!options) {
  87753. options = {};
  87754. }
  87755. if (options.singleGizmo === undefined) {
  87756. options.singleGizmo = true;
  87757. }
  87758. // Instatiate/dispose gizmos based on pointer actions
  87759. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87760. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87761. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87762. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87763. if (options.singleGizmo) {
  87764. _this._clearGizmos();
  87765. }
  87766. // Enable gizmo when mesh is selected
  87767. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87768. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87769. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87770. }
  87771. else {
  87772. if (!options.singleGizmo) {
  87773. // Disable gizmo when clicked again
  87774. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87775. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87776. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87777. }
  87778. }
  87779. }
  87780. else {
  87781. if (options.singleGizmo) {
  87782. // Disable gizmo when clicked away
  87783. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87784. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87785. if (gizmoPick && !gizmoPick.hit) {
  87786. _this._clearGizmos();
  87787. }
  87788. }
  87789. }
  87790. }
  87791. }
  87792. });
  87793. }
  87794. /**
  87795. * Disposes of the gizmo manager
  87796. */
  87797. GizmoManager.prototype.dispose = function () {
  87798. this.scene.onPointerObservable.remove(this._pointerObserver);
  87799. this._clearGizmos();
  87800. this._gizmoLayer.dispose();
  87801. };
  87802. GizmoManager.prototype._clearGizmos = function () {
  87803. for (var key in this._gizmoSet) {
  87804. if (this._gizmoSet.hasOwnProperty(key)) {
  87805. this._gizmoSet[key].positionGizmo.dispose();
  87806. this._gizmoSet[key].rotationGizmo.dispose();
  87807. delete this._gizmoSet[key];
  87808. }
  87809. }
  87810. };
  87811. return GizmoManager;
  87812. }());
  87813. BABYLON.GizmoManager = GizmoManager;
  87814. })(BABYLON || (BABYLON = {}));
  87815. //# sourceMappingURL=babylon.gizmoManager.js.map
  87816. var BABYLON;
  87817. (function (BABYLON) {
  87818. /**
  87819. * Defines a target to use with MorphTargetManager
  87820. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87821. */
  87822. var MorphTarget = /** @class */ (function () {
  87823. /**
  87824. * Creates a new MorphTarget
  87825. * @param name defines the name of the target
  87826. * @param influence defines the influence to use
  87827. */
  87828. function MorphTarget(
  87829. /** defines the name of the target */
  87830. name, influence, scene) {
  87831. if (influence === void 0) { influence = 0; }
  87832. if (scene === void 0) { scene = null; }
  87833. this.name = name;
  87834. /**
  87835. * Gets or sets the list of animations
  87836. */
  87837. this.animations = new Array();
  87838. this._positions = null;
  87839. this._normals = null;
  87840. this._tangents = null;
  87841. /**
  87842. * Observable raised when the influence changes
  87843. */
  87844. this.onInfluenceChanged = new BABYLON.Observable();
  87845. this._animationPropertiesOverride = null;
  87846. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87847. this.influence = influence;
  87848. }
  87849. Object.defineProperty(MorphTarget.prototype, "influence", {
  87850. /**
  87851. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87852. */
  87853. get: function () {
  87854. return this._influence;
  87855. },
  87856. set: function (influence) {
  87857. if (this._influence === influence) {
  87858. return;
  87859. }
  87860. var previous = this._influence;
  87861. this._influence = influence;
  87862. if (this.onInfluenceChanged.hasObservers) {
  87863. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87864. }
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87870. /**
  87871. * Gets or sets the animation properties override
  87872. */
  87873. get: function () {
  87874. if (!this._animationPropertiesOverride && this._scene) {
  87875. return this._scene.animationPropertiesOverride;
  87876. }
  87877. return this._animationPropertiesOverride;
  87878. },
  87879. set: function (value) {
  87880. this._animationPropertiesOverride = value;
  87881. },
  87882. enumerable: true,
  87883. configurable: true
  87884. });
  87885. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87886. /**
  87887. * Gets a boolean defining if the target contains position data
  87888. */
  87889. get: function () {
  87890. return !!this._positions;
  87891. },
  87892. enumerable: true,
  87893. configurable: true
  87894. });
  87895. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87896. /**
  87897. * Gets a boolean defining if the target contains normal data
  87898. */
  87899. get: function () {
  87900. return !!this._normals;
  87901. },
  87902. enumerable: true,
  87903. configurable: true
  87904. });
  87905. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87906. /**
  87907. * Gets a boolean defining if the target contains tangent data
  87908. */
  87909. get: function () {
  87910. return !!this._tangents;
  87911. },
  87912. enumerable: true,
  87913. configurable: true
  87914. });
  87915. /**
  87916. * Affects position data to this target
  87917. * @param data defines the position data to use
  87918. */
  87919. MorphTarget.prototype.setPositions = function (data) {
  87920. this._positions = data;
  87921. };
  87922. /**
  87923. * Gets the position data stored in this target
  87924. * @returns a FloatArray containing the position data (or null if not present)
  87925. */
  87926. MorphTarget.prototype.getPositions = function () {
  87927. return this._positions;
  87928. };
  87929. /**
  87930. * Affects normal data to this target
  87931. * @param data defines the normal data to use
  87932. */
  87933. MorphTarget.prototype.setNormals = function (data) {
  87934. this._normals = data;
  87935. };
  87936. /**
  87937. * Gets the normal data stored in this target
  87938. * @returns a FloatArray containing the normal data (or null if not present)
  87939. */
  87940. MorphTarget.prototype.getNormals = function () {
  87941. return this._normals;
  87942. };
  87943. /**
  87944. * Affects tangent data to this target
  87945. * @param data defines the tangent data to use
  87946. */
  87947. MorphTarget.prototype.setTangents = function (data) {
  87948. this._tangents = data;
  87949. };
  87950. /**
  87951. * Gets the tangent data stored in this target
  87952. * @returns a FloatArray containing the tangent data (or null if not present)
  87953. */
  87954. MorphTarget.prototype.getTangents = function () {
  87955. return this._tangents;
  87956. };
  87957. /**
  87958. * Serializes the current target into a Serialization object
  87959. * @returns the serialized object
  87960. */
  87961. MorphTarget.prototype.serialize = function () {
  87962. var serializationObject = {};
  87963. serializationObject.name = this.name;
  87964. serializationObject.influence = this.influence;
  87965. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87966. if (this.hasNormals) {
  87967. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87968. }
  87969. if (this.hasTangents) {
  87970. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87971. }
  87972. // Animations
  87973. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  87974. return serializationObject;
  87975. };
  87976. // Statics
  87977. /**
  87978. * Creates a new target from serialized data
  87979. * @param serializationObject defines the serialized data to use
  87980. * @returns a new MorphTarget
  87981. */
  87982. MorphTarget.Parse = function (serializationObject) {
  87983. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  87984. result.setPositions(serializationObject.positions);
  87985. if (serializationObject.normals) {
  87986. result.setNormals(serializationObject.normals);
  87987. }
  87988. if (serializationObject.tangents) {
  87989. result.setTangents(serializationObject.tangents);
  87990. }
  87991. // Animations
  87992. if (serializationObject.animations) {
  87993. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  87994. var parsedAnimation = serializationObject.animations[animationIndex];
  87995. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  87996. }
  87997. }
  87998. return result;
  87999. };
  88000. /**
  88001. * Creates a MorphTarget from mesh data
  88002. * @param mesh defines the source mesh
  88003. * @param name defines the name to use for the new target
  88004. * @param influence defines the influence to attach to the target
  88005. * @returns a new MorphTarget
  88006. */
  88007. MorphTarget.FromMesh = function (mesh, name, influence) {
  88008. if (!name) {
  88009. name = mesh.name;
  88010. }
  88011. var result = new MorphTarget(name, influence, mesh.getScene());
  88012. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88014. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88015. }
  88016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88017. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88018. }
  88019. return result;
  88020. };
  88021. return MorphTarget;
  88022. }());
  88023. BABYLON.MorphTarget = MorphTarget;
  88024. })(BABYLON || (BABYLON = {}));
  88025. //# sourceMappingURL=babylon.morphTarget.js.map
  88026. var BABYLON;
  88027. (function (BABYLON) {
  88028. /**
  88029. * This class is used to deform meshes using morphing between different targets
  88030. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88031. */
  88032. var MorphTargetManager = /** @class */ (function () {
  88033. /**
  88034. * Creates a new MorphTargetManager
  88035. * @param scene defines the current scene
  88036. */
  88037. function MorphTargetManager(scene) {
  88038. if (scene === void 0) { scene = null; }
  88039. this._targets = new Array();
  88040. this._targetObservable = new Array();
  88041. this._activeTargets = new BABYLON.SmartArray(16);
  88042. this._supportsNormals = false;
  88043. this._supportsTangents = false;
  88044. this._vertexCount = 0;
  88045. this._uniqueId = 0;
  88046. this._tempInfluences = new Array();
  88047. if (!scene) {
  88048. scene = BABYLON.Engine.LastCreatedScene;
  88049. }
  88050. this._scene = scene;
  88051. if (this._scene) {
  88052. this._scene.morphTargetManagers.push(this);
  88053. this._uniqueId = this._scene.getUniqueId();
  88054. }
  88055. }
  88056. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88057. /**
  88058. * Gets the unique ID of this manager
  88059. */
  88060. get: function () {
  88061. return this._uniqueId;
  88062. },
  88063. enumerable: true,
  88064. configurable: true
  88065. });
  88066. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88067. /**
  88068. * Gets the number of vertices handled by this manager
  88069. */
  88070. get: function () {
  88071. return this._vertexCount;
  88072. },
  88073. enumerable: true,
  88074. configurable: true
  88075. });
  88076. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88077. /**
  88078. * Gets a boolean indicating if this manager supports morphing of normals
  88079. */
  88080. get: function () {
  88081. return this._supportsNormals;
  88082. },
  88083. enumerable: true,
  88084. configurable: true
  88085. });
  88086. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88087. /**
  88088. * Gets a boolean indicating if this manager supports morphing of tangents
  88089. */
  88090. get: function () {
  88091. return this._supportsTangents;
  88092. },
  88093. enumerable: true,
  88094. configurable: true
  88095. });
  88096. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88097. /**
  88098. * Gets the number of targets stored in this manager
  88099. */
  88100. get: function () {
  88101. return this._targets.length;
  88102. },
  88103. enumerable: true,
  88104. configurable: true
  88105. });
  88106. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88107. /**
  88108. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88109. */
  88110. get: function () {
  88111. return this._activeTargets.length;
  88112. },
  88113. enumerable: true,
  88114. configurable: true
  88115. });
  88116. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88117. /**
  88118. * Gets the list of influences (one per target)
  88119. */
  88120. get: function () {
  88121. return this._influences;
  88122. },
  88123. enumerable: true,
  88124. configurable: true
  88125. });
  88126. /**
  88127. * Gets the active target at specified index. An active target is a target with an influence > 0
  88128. * @param index defines the index to check
  88129. * @returns the requested target
  88130. */
  88131. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88132. return this._activeTargets.data[index];
  88133. };
  88134. /**
  88135. * Gets the target at specified index
  88136. * @param index defines the index to check
  88137. * @returns the requested target
  88138. */
  88139. MorphTargetManager.prototype.getTarget = function (index) {
  88140. return this._targets[index];
  88141. };
  88142. /**
  88143. * Add a new target to this manager
  88144. * @param target defines the target to add
  88145. */
  88146. MorphTargetManager.prototype.addTarget = function (target) {
  88147. var _this = this;
  88148. this._targets.push(target);
  88149. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88150. _this._syncActiveTargets(needUpdate);
  88151. }));
  88152. this._syncActiveTargets(true);
  88153. };
  88154. /**
  88155. * Removes a target from the manager
  88156. * @param target defines the target to remove
  88157. */
  88158. MorphTargetManager.prototype.removeTarget = function (target) {
  88159. var index = this._targets.indexOf(target);
  88160. if (index >= 0) {
  88161. this._targets.splice(index, 1);
  88162. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88163. this._syncActiveTargets(true);
  88164. }
  88165. };
  88166. /**
  88167. * Serializes the current manager into a Serialization object
  88168. * @returns the serialized object
  88169. */
  88170. MorphTargetManager.prototype.serialize = function () {
  88171. var serializationObject = {};
  88172. serializationObject.id = this.uniqueId;
  88173. serializationObject.targets = [];
  88174. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88175. var target = _a[_i];
  88176. serializationObject.targets.push(target.serialize());
  88177. }
  88178. return serializationObject;
  88179. };
  88180. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88181. var influenceCount = 0;
  88182. this._activeTargets.reset();
  88183. this._supportsNormals = true;
  88184. this._supportsTangents = true;
  88185. this._vertexCount = 0;
  88186. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88187. var target = _a[_i];
  88188. this._activeTargets.push(target);
  88189. this._tempInfluences[influenceCount++] = target.influence;
  88190. var positions = target.getPositions();
  88191. if (positions) {
  88192. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88193. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88194. var vertexCount = positions.length / 3;
  88195. if (this._vertexCount === 0) {
  88196. this._vertexCount = vertexCount;
  88197. }
  88198. else if (this._vertexCount !== vertexCount) {
  88199. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88200. return;
  88201. }
  88202. }
  88203. }
  88204. if (!this._influences || this._influences.length !== influenceCount) {
  88205. this._influences = new Float32Array(influenceCount);
  88206. }
  88207. for (var index = 0; index < influenceCount; index++) {
  88208. this._influences[index] = this._tempInfluences[index];
  88209. }
  88210. if (needUpdate) {
  88211. this.synchronize();
  88212. }
  88213. };
  88214. /**
  88215. * Syncrhonize the targets with all the meshes using this morph target manager
  88216. */
  88217. MorphTargetManager.prototype.synchronize = function () {
  88218. if (!this._scene) {
  88219. return;
  88220. }
  88221. // Flag meshes as dirty to resync with the active targets
  88222. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88223. var mesh = _a[_i];
  88224. if (mesh.morphTargetManager === this) {
  88225. mesh._syncGeometryWithMorphTargetManager();
  88226. }
  88227. }
  88228. };
  88229. // Statics
  88230. /**
  88231. * Creates a new MorphTargetManager from serialized data
  88232. * @param serializationObject defines the serialized data
  88233. * @param scene defines the hosting scene
  88234. * @returns the new MorphTargetManager
  88235. */
  88236. MorphTargetManager.Parse = function (serializationObject, scene) {
  88237. var result = new MorphTargetManager(scene);
  88238. result._uniqueId = serializationObject.id;
  88239. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88240. var targetData = _a[_i];
  88241. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88242. }
  88243. return result;
  88244. };
  88245. return MorphTargetManager;
  88246. }());
  88247. BABYLON.MorphTargetManager = MorphTargetManager;
  88248. })(BABYLON || (BABYLON = {}));
  88249. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88250. var BABYLON;
  88251. (function (BABYLON) {
  88252. var Octree = /** @class */ (function () {
  88253. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88254. if (maxDepth === void 0) { maxDepth = 2; }
  88255. this.maxDepth = maxDepth;
  88256. this.dynamicContent = new Array();
  88257. this._maxBlockCapacity = maxBlockCapacity || 64;
  88258. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88259. this._creationFunc = creationFunc;
  88260. }
  88261. // Methods
  88262. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88263. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88264. };
  88265. Octree.prototype.addMesh = function (entry) {
  88266. for (var index = 0; index < this.blocks.length; index++) {
  88267. var block = this.blocks[index];
  88268. block.addEntry(entry);
  88269. }
  88270. };
  88271. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88272. this._selectionContent.reset();
  88273. for (var index = 0; index < this.blocks.length; index++) {
  88274. var block = this.blocks[index];
  88275. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88276. }
  88277. if (allowDuplicate) {
  88278. this._selectionContent.concat(this.dynamicContent);
  88279. }
  88280. else {
  88281. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88282. }
  88283. return this._selectionContent;
  88284. };
  88285. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88286. this._selectionContent.reset();
  88287. for (var index = 0; index < this.blocks.length; index++) {
  88288. var block = this.blocks[index];
  88289. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88290. }
  88291. if (allowDuplicate) {
  88292. this._selectionContent.concat(this.dynamicContent);
  88293. }
  88294. else {
  88295. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88296. }
  88297. return this._selectionContent;
  88298. };
  88299. Octree.prototype.intersectsRay = function (ray) {
  88300. this._selectionContent.reset();
  88301. for (var index = 0; index < this.blocks.length; index++) {
  88302. var block = this.blocks[index];
  88303. block.intersectsRay(ray, this._selectionContent);
  88304. }
  88305. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88306. return this._selectionContent;
  88307. };
  88308. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88309. target.blocks = new Array();
  88310. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88311. // Segmenting space
  88312. for (var x = 0; x < 2; x++) {
  88313. for (var y = 0; y < 2; y++) {
  88314. for (var z = 0; z < 2; z++) {
  88315. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88316. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88317. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88318. block.addEntries(entries);
  88319. target.blocks.push(block);
  88320. }
  88321. }
  88322. }
  88323. };
  88324. Octree.CreationFuncForMeshes = function (entry, block) {
  88325. var boundingInfo = entry.getBoundingInfo();
  88326. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88327. block.entries.push(entry);
  88328. }
  88329. };
  88330. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88331. var boundingInfo = entry.getBoundingInfo();
  88332. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88333. block.entries.push(entry);
  88334. }
  88335. };
  88336. return Octree;
  88337. }());
  88338. BABYLON.Octree = Octree;
  88339. })(BABYLON || (BABYLON = {}));
  88340. //# sourceMappingURL=babylon.octree.js.map
  88341. var BABYLON;
  88342. (function (BABYLON) {
  88343. var OctreeBlock = /** @class */ (function () {
  88344. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88345. this.entries = new Array();
  88346. this._boundingVectors = new Array();
  88347. this._capacity = capacity;
  88348. this._depth = depth;
  88349. this._maxDepth = maxDepth;
  88350. this._creationFunc = creationFunc;
  88351. this._minPoint = minPoint;
  88352. this._maxPoint = maxPoint;
  88353. this._boundingVectors.push(minPoint.clone());
  88354. this._boundingVectors.push(maxPoint.clone());
  88355. this._boundingVectors.push(minPoint.clone());
  88356. this._boundingVectors[2].x = maxPoint.x;
  88357. this._boundingVectors.push(minPoint.clone());
  88358. this._boundingVectors[3].y = maxPoint.y;
  88359. this._boundingVectors.push(minPoint.clone());
  88360. this._boundingVectors[4].z = maxPoint.z;
  88361. this._boundingVectors.push(maxPoint.clone());
  88362. this._boundingVectors[5].z = minPoint.z;
  88363. this._boundingVectors.push(maxPoint.clone());
  88364. this._boundingVectors[6].x = minPoint.x;
  88365. this._boundingVectors.push(maxPoint.clone());
  88366. this._boundingVectors[7].y = minPoint.y;
  88367. }
  88368. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88369. // Property
  88370. get: function () {
  88371. return this._capacity;
  88372. },
  88373. enumerable: true,
  88374. configurable: true
  88375. });
  88376. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88377. get: function () {
  88378. return this._minPoint;
  88379. },
  88380. enumerable: true,
  88381. configurable: true
  88382. });
  88383. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88384. get: function () {
  88385. return this._maxPoint;
  88386. },
  88387. enumerable: true,
  88388. configurable: true
  88389. });
  88390. // Methods
  88391. OctreeBlock.prototype.addEntry = function (entry) {
  88392. if (this.blocks) {
  88393. for (var index = 0; index < this.blocks.length; index++) {
  88394. var block = this.blocks[index];
  88395. block.addEntry(entry);
  88396. }
  88397. return;
  88398. }
  88399. this._creationFunc(entry, this);
  88400. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88401. this.createInnerBlocks();
  88402. }
  88403. };
  88404. OctreeBlock.prototype.addEntries = function (entries) {
  88405. for (var index = 0; index < entries.length; index++) {
  88406. var mesh = entries[index];
  88407. this.addEntry(mesh);
  88408. }
  88409. };
  88410. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88411. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88412. if (this.blocks) {
  88413. for (var index = 0; index < this.blocks.length; index++) {
  88414. var block = this.blocks[index];
  88415. block.select(frustumPlanes, selection, allowDuplicate);
  88416. }
  88417. return;
  88418. }
  88419. if (allowDuplicate) {
  88420. selection.concat(this.entries);
  88421. }
  88422. else {
  88423. selection.concatWithNoDuplicate(this.entries);
  88424. }
  88425. }
  88426. };
  88427. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88428. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88429. if (this.blocks) {
  88430. for (var index = 0; index < this.blocks.length; index++) {
  88431. var block = this.blocks[index];
  88432. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88433. }
  88434. return;
  88435. }
  88436. if (allowDuplicate) {
  88437. selection.concat(this.entries);
  88438. }
  88439. else {
  88440. selection.concatWithNoDuplicate(this.entries);
  88441. }
  88442. }
  88443. };
  88444. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88445. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88446. if (this.blocks) {
  88447. for (var index = 0; index < this.blocks.length; index++) {
  88448. var block = this.blocks[index];
  88449. block.intersectsRay(ray, selection);
  88450. }
  88451. return;
  88452. }
  88453. selection.concatWithNoDuplicate(this.entries);
  88454. }
  88455. };
  88456. OctreeBlock.prototype.createInnerBlocks = function () {
  88457. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88458. };
  88459. return OctreeBlock;
  88460. }());
  88461. BABYLON.OctreeBlock = OctreeBlock;
  88462. })(BABYLON || (BABYLON = {}));
  88463. //# sourceMappingURL=babylon.octreeBlock.js.map
  88464. var BABYLON;
  88465. (function (BABYLON) {
  88466. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88467. __extends(VRDistortionCorrectionPostProcess, _super);
  88468. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88469. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88470. 'LensCenter',
  88471. 'Scale',
  88472. 'ScaleIn',
  88473. 'HmdWarpParam'
  88474. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88475. _this._isRightEye = isRightEye;
  88476. _this._distortionFactors = vrMetrics.distortionK;
  88477. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88478. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88479. _this.adaptScaleToCurrentViewport = true;
  88480. _this.onSizeChangedObservable.add(function () {
  88481. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88482. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88483. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88484. });
  88485. _this.onApplyObservable.add(function (effect) {
  88486. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88487. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88488. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88489. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88490. });
  88491. return _this;
  88492. }
  88493. return VRDistortionCorrectionPostProcess;
  88494. }(BABYLON.PostProcess));
  88495. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88496. })(BABYLON || (BABYLON = {}));
  88497. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88498. var BABYLON;
  88499. (function (BABYLON) {
  88500. /**
  88501. * Postprocess used to generate anaglyphic rendering
  88502. */
  88503. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88504. __extends(AnaglyphPostProcess, _super);
  88505. /**
  88506. * Creates a new AnaglyphPostProcess
  88507. * @param name defines postprocess name
  88508. * @param options defines creation options or target ratio scale
  88509. * @param rigCameras defines cameras using this postprocess
  88510. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88511. * @param engine defines hosting engine
  88512. * @param reusable defines if the postprocess will be reused multiple times per frame
  88513. */
  88514. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88515. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88516. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88517. _this.onApplyObservable.add(function (effect) {
  88518. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88519. });
  88520. return _this;
  88521. }
  88522. return AnaglyphPostProcess;
  88523. }(BABYLON.PostProcess));
  88524. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88525. })(BABYLON || (BABYLON = {}));
  88526. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88527. var BABYLON;
  88528. (function (BABYLON) {
  88529. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88530. __extends(StereoscopicInterlacePostProcess, _super);
  88531. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88532. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88533. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88534. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88535. _this.onSizeChangedObservable.add(function () {
  88536. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88537. });
  88538. _this.onApplyObservable.add(function (effect) {
  88539. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88540. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88541. });
  88542. return _this;
  88543. }
  88544. return StereoscopicInterlacePostProcess;
  88545. }(BABYLON.PostProcess));
  88546. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88547. })(BABYLON || (BABYLON = {}));
  88548. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88549. var BABYLON;
  88550. (function (BABYLON) {
  88551. /**
  88552. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88553. * Screen rotation is taken into account.
  88554. */
  88555. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88556. function FreeCameraDeviceOrientationInput() {
  88557. var _this = this;
  88558. this._screenOrientationAngle = 0;
  88559. this._screenQuaternion = new BABYLON.Quaternion();
  88560. this._alpha = 0;
  88561. this._beta = 0;
  88562. this._gamma = 0;
  88563. this._orientationChanged = function () {
  88564. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88565. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88566. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88567. };
  88568. this._deviceOrientation = function (evt) {
  88569. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88570. _this._beta = evt.beta !== null ? evt.beta : 0;
  88571. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88572. };
  88573. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88574. this._orientationChanged();
  88575. }
  88576. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88577. get: function () {
  88578. return this._camera;
  88579. },
  88580. set: function (camera) {
  88581. this._camera = camera;
  88582. if (this._camera != null && !this._camera.rotationQuaternion) {
  88583. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88584. }
  88585. },
  88586. enumerable: true,
  88587. configurable: true
  88588. });
  88589. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88590. window.addEventListener("orientationchange", this._orientationChanged);
  88591. window.addEventListener("deviceorientation", this._deviceOrientation);
  88592. //In certain cases, the attach control is called AFTER orientation was changed,
  88593. //So this is needed.
  88594. this._orientationChanged();
  88595. };
  88596. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88597. window.removeEventListener("orientationchange", this._orientationChanged);
  88598. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88599. };
  88600. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88601. //if no device orientation provided, don't update the rotation.
  88602. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88603. if (!this._alpha)
  88604. return;
  88605. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88606. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88607. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88608. //Mirror on XY Plane
  88609. this._camera.rotationQuaternion.z *= -1;
  88610. this._camera.rotationQuaternion.w *= -1;
  88611. };
  88612. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88613. return "FreeCameraDeviceOrientationInput";
  88614. };
  88615. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88616. return "deviceOrientation";
  88617. };
  88618. return FreeCameraDeviceOrientationInput;
  88619. }());
  88620. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88621. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88622. })(BABYLON || (BABYLON = {}));
  88623. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88624. var BABYLON;
  88625. (function (BABYLON) {
  88626. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88627. function ArcRotateCameraVRDeviceOrientationInput() {
  88628. this.alphaCorrection = 1;
  88629. this.betaCorrection = 1;
  88630. this.gammaCorrection = 1;
  88631. this._alpha = 0;
  88632. this._gamma = 0;
  88633. this._dirty = false;
  88634. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88635. }
  88636. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88637. this.camera.attachControl(element, noPreventDefault);
  88638. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88639. };
  88640. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88641. if (evt.alpha !== null) {
  88642. this._alpha = +evt.alpha | 0;
  88643. }
  88644. if (evt.gamma !== null) {
  88645. this._gamma = +evt.gamma | 0;
  88646. }
  88647. this._dirty = true;
  88648. };
  88649. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88650. if (this._dirty) {
  88651. this._dirty = false;
  88652. if (this._gamma < 0) {
  88653. this._gamma = 180 + this._gamma;
  88654. }
  88655. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88656. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88657. }
  88658. };
  88659. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88660. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88661. };
  88662. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88663. return "ArcRotateCameraVRDeviceOrientationInput";
  88664. };
  88665. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88666. return "VRDeviceOrientation";
  88667. };
  88668. return ArcRotateCameraVRDeviceOrientationInput;
  88669. }());
  88670. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88671. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88672. })(BABYLON || (BABYLON = {}));
  88673. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88674. var BABYLON;
  88675. (function (BABYLON) {
  88676. var VRCameraMetrics = /** @class */ (function () {
  88677. function VRCameraMetrics() {
  88678. this.compensateDistortion = true;
  88679. }
  88680. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88681. get: function () {
  88682. return this.hResolution / (2 * this.vResolution);
  88683. },
  88684. enumerable: true,
  88685. configurable: true
  88686. });
  88687. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88688. get: function () {
  88689. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88690. },
  88691. enumerable: true,
  88692. configurable: true
  88693. });
  88694. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88695. get: function () {
  88696. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88697. var h = (4 * meters) / this.hScreenSize;
  88698. return BABYLON.Matrix.Translation(h, 0, 0);
  88699. },
  88700. enumerable: true,
  88701. configurable: true
  88702. });
  88703. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88704. get: function () {
  88705. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88706. var h = (4 * meters) / this.hScreenSize;
  88707. return BABYLON.Matrix.Translation(-h, 0, 0);
  88708. },
  88709. enumerable: true,
  88710. configurable: true
  88711. });
  88712. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88713. get: function () {
  88714. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88715. },
  88716. enumerable: true,
  88717. configurable: true
  88718. });
  88719. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88720. get: function () {
  88721. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88722. },
  88723. enumerable: true,
  88724. configurable: true
  88725. });
  88726. VRCameraMetrics.GetDefault = function () {
  88727. var result = new VRCameraMetrics();
  88728. result.hResolution = 1280;
  88729. result.vResolution = 800;
  88730. result.hScreenSize = 0.149759993;
  88731. result.vScreenSize = 0.0935999975;
  88732. result.vScreenCenter = 0.0467999987;
  88733. result.eyeToScreenDistance = 0.0410000011;
  88734. result.lensSeparationDistance = 0.0635000020;
  88735. result.interpupillaryDistance = 0.0640000030;
  88736. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88737. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88738. result.postProcessScaleFactor = 1.714605507808412;
  88739. result.lensCenterOffset = 0.151976421;
  88740. return result;
  88741. };
  88742. return VRCameraMetrics;
  88743. }());
  88744. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88745. })(BABYLON || (BABYLON = {}));
  88746. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88747. var BABYLON;
  88748. (function (BABYLON) {
  88749. /**
  88750. * This represents a WebVR camera.
  88751. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88752. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88753. */
  88754. var WebVRFreeCamera = /** @class */ (function (_super) {
  88755. __extends(WebVRFreeCamera, _super);
  88756. /**
  88757. * Instantiates a WebVRFreeCamera.
  88758. * @param name The name of the WebVRFreeCamera
  88759. * @param position The starting anchor position for the camera
  88760. * @param scene The scene the camera belongs to
  88761. * @param webVROptions a set of customizable options for the webVRCamera
  88762. */
  88763. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88764. if (webVROptions === void 0) { webVROptions = {}; }
  88765. var _this = _super.call(this, name, position, scene) || this;
  88766. _this.webVROptions = webVROptions;
  88767. /**
  88768. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88769. */
  88770. _this._vrDevice = null;
  88771. /**
  88772. * The rawPose of the vrDevice.
  88773. */
  88774. _this.rawPose = null;
  88775. _this._specsVersion = "1.1";
  88776. _this._attached = false;
  88777. _this._descendants = [];
  88778. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88779. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88780. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88781. _this._standingMatrix = null;
  88782. /**
  88783. * Represents device position in babylon space.
  88784. */
  88785. _this.devicePosition = BABYLON.Vector3.Zero();
  88786. /**
  88787. * Represents device rotation in babylon space.
  88788. */
  88789. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88790. /**
  88791. * The scale of the device to be used when translating from device space to babylon space.
  88792. */
  88793. _this.deviceScaleFactor = 1;
  88794. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88795. _this._worldToDevice = BABYLON.Matrix.Identity();
  88796. /**
  88797. * References to the webVR controllers for the vrDevice.
  88798. */
  88799. _this.controllers = [];
  88800. /**
  88801. * Emits an event when a controller is attached.
  88802. */
  88803. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88804. /**
  88805. * Emits an event when a controller's mesh has been loaded;
  88806. */
  88807. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88808. /**
  88809. * If the rig cameras be used as parent instead of this camera.
  88810. */
  88811. _this.rigParenting = true;
  88812. _this._defaultHeight = undefined;
  88813. _this._workingVector = BABYLON.Vector3.Zero();
  88814. _this._oneVector = BABYLON.Vector3.One();
  88815. _this._workingMatrix = BABYLON.Matrix.Identity();
  88816. _this._cache.position = BABYLON.Vector3.Zero();
  88817. if (webVROptions.defaultHeight) {
  88818. _this._defaultHeight = webVROptions.defaultHeight;
  88819. _this.position.y = _this._defaultHeight;
  88820. }
  88821. _this.minZ = 0.1;
  88822. //legacy support - the compensation boolean was removed.
  88823. if (arguments.length === 5) {
  88824. _this.webVROptions = arguments[4];
  88825. }
  88826. // default webVR options
  88827. if (_this.webVROptions.trackPosition == undefined) {
  88828. _this.webVROptions.trackPosition = true;
  88829. }
  88830. if (_this.webVROptions.controllerMeshes == undefined) {
  88831. _this.webVROptions.controllerMeshes = true;
  88832. }
  88833. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88834. _this.webVROptions.defaultLightingOnControllers = true;
  88835. }
  88836. _this.rotationQuaternion = new BABYLON.Quaternion();
  88837. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88838. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88839. }
  88840. //enable VR
  88841. var engine = _this.getEngine();
  88842. _this._onVREnabled = function (success) { if (success) {
  88843. _this.initControllers();
  88844. } };
  88845. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88846. engine.initWebVR().add(function (event) {
  88847. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88848. return;
  88849. }
  88850. _this._vrDevice = event.vrDisplay;
  88851. //reset the rig parameters.
  88852. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88853. if (_this._attached) {
  88854. _this.getEngine().enableVR();
  88855. }
  88856. });
  88857. if (typeof (VRFrameData) !== "undefined")
  88858. _this._frameData = new VRFrameData();
  88859. /**
  88860. * The idea behind the following lines:
  88861. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88862. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88863. * the second will not show it correctly.
  88864. *
  88865. * To solve this - each object that has the camera as parent will be added to a protected array.
  88866. * When the rig camera renders, it will take this array and set all of those to be its children.
  88867. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88868. * Amazing!
  88869. */
  88870. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88871. if (camera.parent === _this && _this.rigParenting) {
  88872. _this._descendants = _this.getDescendants(true, function (n) {
  88873. // don't take the cameras or the controllers!
  88874. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88875. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88876. return !isController && !isRigCamera;
  88877. });
  88878. _this._descendants.forEach(function (node) {
  88879. node.parent = camera;
  88880. });
  88881. }
  88882. });
  88883. scene.onAfterCameraRenderObservable.add(function (camera) {
  88884. if (camera.parent === _this && _this.rigParenting) {
  88885. _this._descendants.forEach(function (node) {
  88886. node.parent = _this;
  88887. });
  88888. }
  88889. });
  88890. return _this;
  88891. }
  88892. /**
  88893. * Gets the device distance from the ground in meters.
  88894. * @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.
  88895. */
  88896. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88897. if (this._standingMatrix) {
  88898. // Add standing matrix offset to get real offset from ground in room
  88899. this._standingMatrix.getTranslationToRef(this._workingVector);
  88900. return this._deviceRoomPosition.y + this._workingVector.y;
  88901. }
  88902. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88903. return this._defaultHeight || 0;
  88904. };
  88905. /**
  88906. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88907. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88908. */
  88909. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88910. var _this = this;
  88911. if (callback === void 0) { callback = function (bool) { }; }
  88912. // Use standing matrix if available
  88913. this.getEngine().initWebVRAsync().then(function (result) {
  88914. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88915. callback(false);
  88916. }
  88917. else {
  88918. _this._standingMatrix = new BABYLON.Matrix();
  88919. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88920. if (!_this.getScene().useRightHandedSystem) {
  88921. [2, 6, 8, 9, 14].forEach(function (num) {
  88922. if (_this._standingMatrix) {
  88923. _this._standingMatrix.m[num] *= -1;
  88924. }
  88925. });
  88926. }
  88927. callback(true);
  88928. }
  88929. });
  88930. };
  88931. /**
  88932. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88933. * @returns A promise with a boolean set to if the standing matrix is supported.
  88934. */
  88935. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88936. var _this = this;
  88937. return new Promise(function (res, rej) {
  88938. _this.useStandingMatrix(function (supported) {
  88939. res(supported);
  88940. });
  88941. });
  88942. };
  88943. /**
  88944. * Disposes the camera
  88945. */
  88946. WebVRFreeCamera.prototype.dispose = function () {
  88947. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88948. _super.prototype.dispose.call(this);
  88949. };
  88950. /**
  88951. * Gets a vrController by name.
  88952. * @param name The name of the controller to retreive
  88953. * @returns the controller matching the name specified or null if not found
  88954. */
  88955. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88956. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88957. var gp = _a[_i];
  88958. if (gp.hand === name) {
  88959. return gp;
  88960. }
  88961. }
  88962. return null;
  88963. };
  88964. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88965. /**
  88966. * The controller corrisponding to the users left hand.
  88967. */
  88968. get: function () {
  88969. if (!this._leftController) {
  88970. this._leftController = this.getControllerByName("left");
  88971. }
  88972. return this._leftController;
  88973. },
  88974. enumerable: true,
  88975. configurable: true
  88976. });
  88977. ;
  88978. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  88979. /**
  88980. * The controller corrisponding to the users right hand.
  88981. */
  88982. get: function () {
  88983. if (!this._rightController) {
  88984. this._rightController = this.getControllerByName("right");
  88985. }
  88986. return this._rightController;
  88987. },
  88988. enumerable: true,
  88989. configurable: true
  88990. });
  88991. ;
  88992. /**
  88993. * Casts a ray forward from the vrCamera's gaze.
  88994. * @param length Length of the ray (default: 100)
  88995. * @returns the ray corrisponding to the gaze
  88996. */
  88997. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  88998. if (length === void 0) { length = 100; }
  88999. if (this.leftCamera) {
  89000. // Use left eye to avoid computation to compute center on every call
  89001. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89002. }
  89003. else {
  89004. return _super.prototype.getForwardRay.call(this, length);
  89005. }
  89006. };
  89007. /**
  89008. * Updates the camera based on device's frame data
  89009. */
  89010. WebVRFreeCamera.prototype._checkInputs = function () {
  89011. if (this._vrDevice && this._vrDevice.isPresenting) {
  89012. this._vrDevice.getFrameData(this._frameData);
  89013. this.updateFromDevice(this._frameData.pose);
  89014. }
  89015. _super.prototype._checkInputs.call(this);
  89016. };
  89017. /**
  89018. * Updates the poseControlled values based on the input device pose.
  89019. * @param poseData Pose coming from the device
  89020. */
  89021. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89022. if (poseData && poseData.orientation) {
  89023. this.rawPose = poseData;
  89024. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89025. if (this.getScene().useRightHandedSystem) {
  89026. this._deviceRoomRotationQuaternion.z *= -1;
  89027. this._deviceRoomRotationQuaternion.w *= -1;
  89028. }
  89029. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89030. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89031. if (this.getScene().useRightHandedSystem) {
  89032. this._deviceRoomPosition.z *= -1;
  89033. }
  89034. }
  89035. }
  89036. };
  89037. /**
  89038. * WebVR's attach control will start broadcasting frames to the device.
  89039. * Note that in certain browsers (chrome for example) this function must be called
  89040. * within a user-interaction callback. Example:
  89041. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89042. *
  89043. * @param element html element to attach the vrDevice to
  89044. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89045. */
  89046. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89047. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89048. this._attached = true;
  89049. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89050. if (this._vrDevice) {
  89051. this.getEngine().enableVR();
  89052. }
  89053. };
  89054. /**
  89055. * Detaches the camera from the html element and disables VR
  89056. *
  89057. * @param element html element to detach from
  89058. */
  89059. WebVRFreeCamera.prototype.detachControl = function (element) {
  89060. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89061. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89062. _super.prototype.detachControl.call(this, element);
  89063. this._attached = false;
  89064. this.getEngine().disableVR();
  89065. };
  89066. /**
  89067. * @returns the name of this class
  89068. */
  89069. WebVRFreeCamera.prototype.getClassName = function () {
  89070. return "WebVRFreeCamera";
  89071. };
  89072. /**
  89073. * Calls resetPose on the vrDisplay
  89074. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89075. */
  89076. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89077. //uses the vrDisplay's "resetPose()".
  89078. //pitch and roll won't be affected.
  89079. this._vrDevice.resetPose();
  89080. };
  89081. /**
  89082. * Updates the rig cameras (left and right eye)
  89083. */
  89084. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89085. var camLeft = this._rigCameras[0];
  89086. var camRight = this._rigCameras[1];
  89087. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89088. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89089. camLeft.position.copyFrom(this._deviceRoomPosition);
  89090. camRight.position.copyFrom(this._deviceRoomPosition);
  89091. };
  89092. /**
  89093. * Updates the cached values of the camera
  89094. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89095. */
  89096. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89097. var _this = this;
  89098. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89099. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89100. if (!this.updateCacheCalled) {
  89101. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89102. this.updateCacheCalled = true;
  89103. this.update();
  89104. }
  89105. // Set working vector to the device position in room space rotated by the new rotation
  89106. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89107. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89108. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89109. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89110. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89111. // Add translation from anchor position
  89112. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89113. this._workingVector.addInPlace(this.position);
  89114. this._workingVector.subtractInPlace(this._cache.position);
  89115. this._deviceToWorld.setTranslation(this._workingVector);
  89116. // Set an inverted matrix to be used when updating the camera
  89117. this._deviceToWorld.invertToRef(this._worldToDevice);
  89118. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89119. this.controllers.forEach(function (controller) {
  89120. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89121. controller.update();
  89122. });
  89123. }
  89124. if (!ignoreParentClass) {
  89125. _super.prototype._updateCache.call(this);
  89126. }
  89127. this.updateCacheCalled = false;
  89128. };
  89129. /**
  89130. * Updates the current device position and rotation in the babylon world
  89131. */
  89132. WebVRFreeCamera.prototype.update = function () {
  89133. // Get current device position in babylon world
  89134. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89135. // Get current device rotation in babylon world
  89136. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89137. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89138. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89139. _super.prototype.update.call(this);
  89140. };
  89141. /**
  89142. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89143. * @returns an identity matrix
  89144. */
  89145. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89146. return BABYLON.Matrix.Identity();
  89147. };
  89148. /**
  89149. * This function is called by the two RIG cameras.
  89150. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89151. */
  89152. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89153. var _this = this;
  89154. // Update the parent camera prior to using a child camera to avoid desynchronization
  89155. var parentCamera = this._cameraRigParams["parentCamera"];
  89156. parentCamera._updateCache();
  89157. //WebVR 1.1
  89158. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89159. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89160. if (!this.getScene().useRightHandedSystem) {
  89161. [2, 6, 8, 9, 14].forEach(function (num) {
  89162. _this._webvrViewMatrix.m[num] *= -1;
  89163. });
  89164. }
  89165. // update the camera rotation matrix
  89166. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89167. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89168. // Computing target and final matrix
  89169. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89170. // should the view matrix be updated with scale and position offset?
  89171. if (parentCamera.deviceScaleFactor !== 1) {
  89172. this._webvrViewMatrix.invert();
  89173. // scale the position, if set
  89174. if (parentCamera.deviceScaleFactor) {
  89175. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89176. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89177. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89178. }
  89179. this._webvrViewMatrix.invert();
  89180. }
  89181. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89182. // Compute global position
  89183. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89184. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89185. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89186. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89187. this._markSyncedWithParent();
  89188. return this._webvrViewMatrix;
  89189. };
  89190. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89191. var _this = this;
  89192. var parentCamera = this.parent;
  89193. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89194. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89195. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89196. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89197. //babylon compatible matrix
  89198. if (!this.getScene().useRightHandedSystem) {
  89199. [8, 9, 10, 11].forEach(function (num) {
  89200. _this._projectionMatrix.m[num] *= -1;
  89201. });
  89202. }
  89203. return this._projectionMatrix;
  89204. };
  89205. /**
  89206. * Initializes the controllers and their meshes
  89207. */
  89208. WebVRFreeCamera.prototype.initControllers = function () {
  89209. var _this = this;
  89210. this.controllers = [];
  89211. var manager = this.getScene().gamepadManager;
  89212. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89213. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89214. var webVrController = gamepad;
  89215. if (webVrController.defaultModel) {
  89216. webVrController.defaultModel.setEnabled(false);
  89217. }
  89218. if (webVrController.hand === "right") {
  89219. _this._rightController = null;
  89220. }
  89221. if (webVrController.hand === "left") {
  89222. _this._leftController = null;
  89223. }
  89224. var controllerIndex = _this.controllers.indexOf(webVrController);
  89225. if (controllerIndex !== -1) {
  89226. _this.controllers.splice(controllerIndex, 1);
  89227. }
  89228. }
  89229. });
  89230. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89231. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89232. var webVrController_1 = gamepad;
  89233. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89234. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89235. if (_this.webVROptions.controllerMeshes) {
  89236. if (webVrController_1.defaultModel) {
  89237. webVrController_1.defaultModel.setEnabled(true);
  89238. }
  89239. else {
  89240. // Load the meshes
  89241. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89242. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89243. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89244. if (_this.webVROptions.defaultLightingOnControllers) {
  89245. if (!_this._lightOnControllers) {
  89246. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89247. }
  89248. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89249. var children = mesh.getChildren();
  89250. if (children.length !== 0) {
  89251. children.forEach(function (mesh) {
  89252. light.includedOnlyMeshes.push(mesh);
  89253. activateLightOnSubMeshes_1(mesh, light);
  89254. });
  89255. }
  89256. };
  89257. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89258. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89259. }
  89260. });
  89261. }
  89262. }
  89263. webVrController_1.attachToPoseControlledCamera(_this);
  89264. // since this is async - sanity check. Is the controller already stored?
  89265. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89266. //add to the controllers array
  89267. _this.controllers.push(webVrController_1);
  89268. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89269. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89270. // So we're overriding setting left & right manually to be sure
  89271. var firstViveWandDetected = false;
  89272. for (var i = 0; i < _this.controllers.length; i++) {
  89273. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89274. if (!firstViveWandDetected) {
  89275. firstViveWandDetected = true;
  89276. _this.controllers[i].hand = "left";
  89277. }
  89278. else {
  89279. _this.controllers[i].hand = "right";
  89280. }
  89281. }
  89282. }
  89283. //did we find enough controllers? Great! let the developer know.
  89284. if (_this.controllers.length >= 2) {
  89285. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89286. }
  89287. }
  89288. }
  89289. });
  89290. };
  89291. return WebVRFreeCamera;
  89292. }(BABYLON.FreeCamera));
  89293. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89294. })(BABYLON || (BABYLON = {}));
  89295. //# sourceMappingURL=babylon.webVRCamera.js.map
  89296. var BABYLON;
  89297. (function (BABYLON) {
  89298. // We're mainly based on the logic defined into the FreeCamera code
  89299. /**
  89300. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89301. * being tilted forward or back and left or right.
  89302. */
  89303. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89304. __extends(DeviceOrientationCamera, _super);
  89305. /**
  89306. * Creates a new device orientation camera
  89307. * @param name The name of the camera
  89308. * @param position The start position camera
  89309. * @param scene The scene the camera belongs to
  89310. */
  89311. function DeviceOrientationCamera(name, position, scene) {
  89312. var _this = _super.call(this, name, position, scene) || this;
  89313. _this._quaternionCache = new BABYLON.Quaternion();
  89314. _this.inputs.addDeviceOrientation();
  89315. return _this;
  89316. }
  89317. /**
  89318. * Gets the current instance class name ("DeviceOrientationCamera").
  89319. * This helps avoiding instanceof at run time.
  89320. * @returns the class name
  89321. */
  89322. DeviceOrientationCamera.prototype.getClassName = function () {
  89323. return "DeviceOrientationCamera";
  89324. };
  89325. /**
  89326. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89327. */
  89328. DeviceOrientationCamera.prototype._checkInputs = function () {
  89329. _super.prototype._checkInputs.call(this);
  89330. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89331. if (this._initialQuaternion) {
  89332. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89333. }
  89334. };
  89335. /**
  89336. * Reset the camera to its default orientation on the specified axis only.
  89337. * @param axis The axis to reset
  89338. */
  89339. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89340. var _this = this;
  89341. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89342. //can only work if this camera has a rotation quaternion already.
  89343. if (!this.rotationQuaternion)
  89344. return;
  89345. if (!this._initialQuaternion) {
  89346. this._initialQuaternion = new BABYLON.Quaternion();
  89347. }
  89348. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89349. ['x', 'y', 'z'].forEach(function (axisName) {
  89350. if (!axis[axisName]) {
  89351. _this._initialQuaternion[axisName] = 0;
  89352. }
  89353. else {
  89354. _this._initialQuaternion[axisName] *= -1;
  89355. }
  89356. });
  89357. this._initialQuaternion.normalize();
  89358. //force rotation update
  89359. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89360. };
  89361. return DeviceOrientationCamera;
  89362. }(BABYLON.FreeCamera));
  89363. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89364. })(BABYLON || (BABYLON = {}));
  89365. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89366. var BABYLON;
  89367. (function (BABYLON) {
  89368. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89369. __extends(VRDeviceOrientationFreeCamera, _super);
  89370. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89371. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89372. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89373. var _this = _super.call(this, name, position, scene) || this;
  89374. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89375. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89376. return _this;
  89377. }
  89378. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89379. return "VRDeviceOrientationFreeCamera";
  89380. };
  89381. return VRDeviceOrientationFreeCamera;
  89382. }(BABYLON.DeviceOrientationCamera));
  89383. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89384. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89385. __extends(VRDeviceOrientationGamepadCamera, _super);
  89386. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89387. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89388. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89389. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89390. _this.inputs.addGamepad();
  89391. return _this;
  89392. }
  89393. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89394. return "VRDeviceOrientationGamepadCamera";
  89395. };
  89396. return VRDeviceOrientationGamepadCamera;
  89397. }(VRDeviceOrientationFreeCamera));
  89398. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89399. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89400. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89401. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89402. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89403. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89404. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89405. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89406. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89407. _this.inputs.addVRDeviceOrientation();
  89408. return _this;
  89409. }
  89410. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89411. return "VRDeviceOrientationArcRotateCamera";
  89412. };
  89413. return VRDeviceOrientationArcRotateCamera;
  89414. }(BABYLON.ArcRotateCamera));
  89415. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89416. })(BABYLON || (BABYLON = {}));
  89417. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89418. var BABYLON;
  89419. (function (BABYLON) {
  89420. /**
  89421. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89422. */
  89423. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89424. __extends(AnaglyphFreeCamera, _super);
  89425. /**
  89426. * Creates a new AnaglyphFreeCamera
  89427. * @param name defines camera name
  89428. * @param position defines initial position
  89429. * @param interaxialDistance defines distance between each color axis
  89430. * @param scene defines the hosting scene
  89431. */
  89432. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89433. var _this = _super.call(this, name, position, scene) || this;
  89434. _this.interaxialDistance = interaxialDistance;
  89435. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89436. return _this;
  89437. }
  89438. /**
  89439. * Gets camera class name
  89440. * @returns AnaglyphFreeCamera
  89441. */
  89442. AnaglyphFreeCamera.prototype.getClassName = function () {
  89443. return "AnaglyphFreeCamera";
  89444. };
  89445. return AnaglyphFreeCamera;
  89446. }(BABYLON.FreeCamera));
  89447. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89448. /**
  89449. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89450. */
  89451. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89452. __extends(AnaglyphArcRotateCamera, _super);
  89453. /**
  89454. * Creates a new AnaglyphArcRotateCamera
  89455. * @param name defines camera name
  89456. * @param alpha defines alpha angle (in radians)
  89457. * @param beta defines beta angle (in radians)
  89458. * @param radius defines radius
  89459. * @param target defines camera target
  89460. * @param interaxialDistance defines distance between each color axis
  89461. * @param scene defines the hosting scene
  89462. */
  89463. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89464. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89465. _this.interaxialDistance = interaxialDistance;
  89466. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89467. return _this;
  89468. }
  89469. /**
  89470. * Gets camera class name
  89471. * @returns AnaglyphArcRotateCamera
  89472. */
  89473. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89474. return "AnaglyphArcRotateCamera";
  89475. };
  89476. return AnaglyphArcRotateCamera;
  89477. }(BABYLON.ArcRotateCamera));
  89478. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89479. /**
  89480. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89481. */
  89482. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89483. __extends(AnaglyphGamepadCamera, _super);
  89484. /**
  89485. * Creates a new AnaglyphGamepadCamera
  89486. * @param name defines camera name
  89487. * @param position defines initial position
  89488. * @param interaxialDistance defines distance between each color axis
  89489. * @param scene defines the hosting scene
  89490. */
  89491. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89492. var _this = _super.call(this, name, position, scene) || this;
  89493. _this.interaxialDistance = interaxialDistance;
  89494. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89495. return _this;
  89496. }
  89497. /**
  89498. * Gets camera class name
  89499. * @returns AnaglyphGamepadCamera
  89500. */
  89501. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89502. return "AnaglyphGamepadCamera";
  89503. };
  89504. return AnaglyphGamepadCamera;
  89505. }(BABYLON.GamepadCamera));
  89506. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89507. /**
  89508. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89509. */
  89510. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89511. __extends(AnaglyphUniversalCamera, _super);
  89512. /**
  89513. * Creates a new AnaglyphUniversalCamera
  89514. * @param name defines camera name
  89515. * @param position defines initial position
  89516. * @param interaxialDistance defines distance between each color axis
  89517. * @param scene defines the hosting scene
  89518. */
  89519. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89520. var _this = _super.call(this, name, position, scene) || this;
  89521. _this.interaxialDistance = interaxialDistance;
  89522. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89523. return _this;
  89524. }
  89525. /**
  89526. * Gets camera class name
  89527. * @returns AnaglyphUniversalCamera
  89528. */
  89529. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89530. return "AnaglyphUniversalCamera";
  89531. };
  89532. return AnaglyphUniversalCamera;
  89533. }(BABYLON.UniversalCamera));
  89534. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89535. /**
  89536. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89537. */
  89538. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89539. __extends(StereoscopicFreeCamera, _super);
  89540. /**
  89541. * Creates a new StereoscopicFreeCamera
  89542. * @param name defines camera name
  89543. * @param position defines initial position
  89544. * @param interaxialDistance defines distance between each color axis
  89545. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89546. * @param scene defines the hosting scene
  89547. */
  89548. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89549. var _this = _super.call(this, name, position, scene) || this;
  89550. _this.interaxialDistance = interaxialDistance;
  89551. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89552. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89553. return _this;
  89554. }
  89555. /**
  89556. * Gets camera class name
  89557. * @returns StereoscopicFreeCamera
  89558. */
  89559. StereoscopicFreeCamera.prototype.getClassName = function () {
  89560. return "StereoscopicFreeCamera";
  89561. };
  89562. return StereoscopicFreeCamera;
  89563. }(BABYLON.FreeCamera));
  89564. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89565. /**
  89566. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89567. */
  89568. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89569. __extends(StereoscopicArcRotateCamera, _super);
  89570. /**
  89571. * Creates a new StereoscopicArcRotateCamera
  89572. * @param name defines camera name
  89573. * @param alpha defines alpha angle (in radians)
  89574. * @param beta defines beta angle (in radians)
  89575. * @param radius defines radius
  89576. * @param target defines camera target
  89577. * @param interaxialDistance defines distance between each color axis
  89578. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89579. * @param scene defines the hosting scene
  89580. */
  89581. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89582. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89583. _this.interaxialDistance = interaxialDistance;
  89584. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89585. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89586. return _this;
  89587. }
  89588. /**
  89589. * Gets camera class name
  89590. * @returns StereoscopicArcRotateCamera
  89591. */
  89592. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89593. return "StereoscopicArcRotateCamera";
  89594. };
  89595. return StereoscopicArcRotateCamera;
  89596. }(BABYLON.ArcRotateCamera));
  89597. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89598. /**
  89599. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89600. */
  89601. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89602. __extends(StereoscopicGamepadCamera, _super);
  89603. /**
  89604. * Creates a new StereoscopicGamepadCamera
  89605. * @param name defines camera name
  89606. * @param position defines initial position
  89607. * @param interaxialDistance defines distance between each color axis
  89608. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89609. * @param scene defines the hosting scene
  89610. */
  89611. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89612. var _this = _super.call(this, name, position, scene) || this;
  89613. _this.interaxialDistance = interaxialDistance;
  89614. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89615. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89616. return _this;
  89617. }
  89618. /**
  89619. * Gets camera class name
  89620. * @returns StereoscopicGamepadCamera
  89621. */
  89622. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89623. return "StereoscopicGamepadCamera";
  89624. };
  89625. return StereoscopicGamepadCamera;
  89626. }(BABYLON.GamepadCamera));
  89627. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89628. /**
  89629. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89630. */
  89631. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89632. __extends(StereoscopicUniversalCamera, _super);
  89633. /**
  89634. * Creates a new StereoscopicUniversalCamera
  89635. * @param name defines camera name
  89636. * @param position defines initial position
  89637. * @param interaxialDistance defines distance between each color axis
  89638. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89639. * @param scene defines the hosting scene
  89640. */
  89641. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89642. var _this = _super.call(this, name, position, scene) || this;
  89643. _this.interaxialDistance = interaxialDistance;
  89644. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89645. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89646. return _this;
  89647. }
  89648. /**
  89649. * Gets camera class name
  89650. * @returns StereoscopicUniversalCamera
  89651. */
  89652. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89653. return "StereoscopicUniversalCamera";
  89654. };
  89655. return StereoscopicUniversalCamera;
  89656. }(BABYLON.UniversalCamera));
  89657. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89658. })(BABYLON || (BABYLON = {}));
  89659. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89660. var BABYLON;
  89661. (function (BABYLON) {
  89662. var VRExperienceHelperGazer = /** @class */ (function () {
  89663. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89664. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89665. this.scene = scene;
  89666. this._pointerDownOnMeshAsked = false;
  89667. this._isActionableMesh = false;
  89668. this._teleportationRequestInitiated = false;
  89669. this._teleportationBackRequestInitiated = false;
  89670. this._rotationRightAsked = false;
  89671. this._rotationLeftAsked = false;
  89672. this._dpadPressed = true;
  89673. this._activePointer = false;
  89674. this._id = VRExperienceHelperGazer._idCounter++;
  89675. // Gaze tracker
  89676. if (!gazeTrackerToClone) {
  89677. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89678. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89679. this._gazeTracker.isPickable = false;
  89680. this._gazeTracker.isVisible = false;
  89681. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89682. targetMat.specularColor = BABYLON.Color3.Black();
  89683. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89684. targetMat.backFaceCulling = false;
  89685. this._gazeTracker.material = targetMat;
  89686. }
  89687. else {
  89688. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89689. }
  89690. }
  89691. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89692. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89693. };
  89694. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89695. this._pointerDownOnMeshAsked = true;
  89696. if (this._currentHit) {
  89697. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89698. }
  89699. };
  89700. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89701. if (this._currentHit) {
  89702. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89703. }
  89704. this._pointerDownOnMeshAsked = false;
  89705. };
  89706. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89707. this._activePointer = true;
  89708. };
  89709. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89710. this._activePointer = false;
  89711. };
  89712. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89713. if (distance === void 0) { distance = 100; }
  89714. };
  89715. VRExperienceHelperGazer.prototype.dispose = function () {
  89716. this._interactionsEnabled = false;
  89717. this._teleportationEnabled = false;
  89718. if (this._gazeTracker) {
  89719. this._gazeTracker.dispose();
  89720. }
  89721. };
  89722. VRExperienceHelperGazer._idCounter = 0;
  89723. return VRExperienceHelperGazer;
  89724. }());
  89725. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89726. __extends(VRExperienceHelperControllerGazer, _super);
  89727. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89728. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89729. _this.webVRController = webVRController;
  89730. // Laser pointer
  89731. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89732. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89733. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89734. laserPointerMaterial.alpha = 0.6;
  89735. _this._laserPointer.material = laserPointerMaterial;
  89736. _this._laserPointer.rotation.x = Math.PI / 2;
  89737. _this._laserPointer.position.z = -0.5;
  89738. _this._laserPointer.isVisible = false;
  89739. if (!webVRController.mesh) {
  89740. // Create an empty mesh that is used prior to loading the high quality model
  89741. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89742. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89743. preloadPointerPose.rotation.x = -0.7;
  89744. preloadMesh.addChild(preloadPointerPose);
  89745. webVRController.attachToMesh(preloadMesh);
  89746. }
  89747. _this._setLaserPointerParent(webVRController.mesh);
  89748. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89749. _this._setLaserPointerParent(mesh);
  89750. });
  89751. return _this;
  89752. }
  89753. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89754. return this.webVRController.getForwardRay(length);
  89755. };
  89756. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89757. _super.prototype._activatePointer.call(this);
  89758. this._laserPointer.isVisible = true;
  89759. };
  89760. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89761. _super.prototype._deactivatePointer.call(this);
  89762. this._laserPointer.isVisible = false;
  89763. };
  89764. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89765. this._laserPointer.material.emissiveColor = color;
  89766. };
  89767. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89768. var makeNotPick = function (root) {
  89769. root.name += " laserPointer";
  89770. root.getChildMeshes().forEach(function (c) {
  89771. makeNotPick(c);
  89772. });
  89773. };
  89774. makeNotPick(mesh);
  89775. var childMeshes = mesh.getChildMeshes();
  89776. this.webVRController._pointingPoseNode = null;
  89777. for (var i = 0; i < childMeshes.length; i++) {
  89778. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89779. mesh = childMeshes[i];
  89780. this.webVRController._pointingPoseNode = mesh;
  89781. break;
  89782. }
  89783. }
  89784. this._laserPointer.parent = mesh;
  89785. };
  89786. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89787. if (distance === void 0) { distance = 100; }
  89788. this._laserPointer.scaling.y = distance;
  89789. this._laserPointer.position.z = -distance / 2;
  89790. };
  89791. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89792. _super.prototype.dispose.call(this);
  89793. this._laserPointer.dispose();
  89794. if (this._meshAttachedObserver) {
  89795. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89796. }
  89797. };
  89798. return VRExperienceHelperControllerGazer;
  89799. }(VRExperienceHelperGazer));
  89800. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89801. __extends(VRExperienceHelperCameraGazer, _super);
  89802. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89803. var _this = _super.call(this, scene) || this;
  89804. _this.getCamera = getCamera;
  89805. return _this;
  89806. }
  89807. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89808. var camera = this.getCamera();
  89809. if (camera) {
  89810. return camera.getForwardRay(length);
  89811. }
  89812. else {
  89813. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89814. }
  89815. };
  89816. return VRExperienceHelperCameraGazer;
  89817. }(VRExperienceHelperGazer));
  89818. /**
  89819. * Helps to quickly add VR support to an existing scene.
  89820. * See http://doc.babylonjs.com/how_to/webvr_helper
  89821. */
  89822. var VRExperienceHelper = /** @class */ (function () {
  89823. /**
  89824. * Instantiates a VRExperienceHelper.
  89825. * Helps to quickly add VR support to an existing scene.
  89826. * @param scene The scene the VRExperienceHelper belongs to.
  89827. * @param webVROptions Options to modify the vr experience helper's behavior.
  89828. */
  89829. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89830. if (webVROptions === void 0) { webVROptions = {}; }
  89831. var _this = this;
  89832. this.webVROptions = webVROptions;
  89833. // Can the system support WebVR, even if a headset isn't plugged in?
  89834. this._webVRsupported = false;
  89835. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89836. this._webVRready = false;
  89837. // Are we waiting for the requestPresent callback to complete?
  89838. this._webVRrequesting = false;
  89839. // Are we presenting to the headset right now?
  89840. this._webVRpresenting = false;
  89841. // Are we presenting in the fullscreen fallback?
  89842. this._fullscreenVRpresenting = false;
  89843. /**
  89844. * Observable raised when entering VR.
  89845. */
  89846. this.onEnteringVRObservable = new BABYLON.Observable();
  89847. /**
  89848. * Observable raised when exiting VR.
  89849. */
  89850. this.onExitingVRObservable = new BABYLON.Observable();
  89851. /**
  89852. * Observable raised when controller mesh is loaded.
  89853. */
  89854. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89855. this._useCustomVRButton = false;
  89856. this._teleportationRequested = false;
  89857. this._teleportActive = false;
  89858. this._floorMeshesCollection = [];
  89859. this._rotationAllowed = true;
  89860. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89861. this._isDefaultTeleportationTarget = true;
  89862. this._teleportationFillColor = "#444444";
  89863. this._teleportationBorderColor = "#FFFFFF";
  89864. this._rotationAngle = 0;
  89865. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89866. this._padSensibilityUp = 0.65;
  89867. this._padSensibilityDown = 0.35;
  89868. this.leftController = null;
  89869. this.rightController = null;
  89870. /**
  89871. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89872. */
  89873. this.onNewMeshSelected = new BABYLON.Observable();
  89874. /**
  89875. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89876. */
  89877. this.onNewMeshPicked = new BABYLON.Observable();
  89878. /**
  89879. * Observable raised before camera teleportation
  89880. */
  89881. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89882. /**
  89883. * Observable raised after camera teleportation
  89884. */
  89885. this.onAfterCameraTeleport = new BABYLON.Observable();
  89886. /**
  89887. * Observable raised when current selected mesh gets unselected
  89888. */
  89889. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89890. /**
  89891. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89892. */
  89893. this.teleportationEnabled = true;
  89894. this._teleportationInitialized = false;
  89895. this._interactionsEnabled = false;
  89896. this._interactionsRequested = false;
  89897. this._displayGaze = true;
  89898. this._displayLaserPointer = true;
  89899. this._onResize = function () {
  89900. _this.moveButtonToBottomRight();
  89901. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89902. _this.exitVR();
  89903. }
  89904. };
  89905. this._onFullscreenChange = function () {
  89906. if (document.fullscreen !== undefined) {
  89907. _this._fullscreenVRpresenting = document.fullscreen;
  89908. }
  89909. else if (document.mozFullScreen !== undefined) {
  89910. _this._fullscreenVRpresenting = document.mozFullScreen;
  89911. }
  89912. else if (document.webkitIsFullScreen !== undefined) {
  89913. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89914. }
  89915. else if (document.msIsFullScreen !== undefined) {
  89916. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89917. }
  89918. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89919. _this.exitVR();
  89920. if (!_this._useCustomVRButton) {
  89921. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89922. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89923. }
  89924. }
  89925. };
  89926. this.beforeRender = function () {
  89927. if (_this.leftController && _this.leftController._activePointer) {
  89928. _this._castRayAndSelectObject(_this.leftController);
  89929. }
  89930. if (_this.rightController && _this.rightController._activePointer) {
  89931. _this._castRayAndSelectObject(_this.rightController);
  89932. }
  89933. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89934. _this._castRayAndSelectObject(_this._cameraGazer);
  89935. }
  89936. else {
  89937. _this._cameraGazer._gazeTracker.isVisible = false;
  89938. }
  89939. };
  89940. this._onNewGamepadConnected = function (gamepad) {
  89941. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89942. if (gamepad.leftStick) {
  89943. gamepad.onleftstickchanged(function (stickValues) {
  89944. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89945. // Listening to classic/xbox gamepad only if no VR controller is active
  89946. if ((!_this.leftController && !_this.rightController) ||
  89947. ((_this.leftController && !_this.leftController._activePointer) &&
  89948. (_this.rightController && !_this.rightController._activePointer))) {
  89949. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89950. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89951. }
  89952. }
  89953. });
  89954. }
  89955. if (gamepad.rightStick) {
  89956. gamepad.onrightstickchanged(function (stickValues) {
  89957. if (_this._teleportationInitialized) {
  89958. _this._checkRotate(stickValues, _this._cameraGazer);
  89959. }
  89960. });
  89961. }
  89962. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89963. gamepad.onbuttondown(function (buttonPressed) {
  89964. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89965. _this._cameraGazer._selectionPointerDown();
  89966. }
  89967. });
  89968. gamepad.onbuttonup(function (buttonPressed) {
  89969. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89970. _this._cameraGazer._selectionPointerUp();
  89971. }
  89972. });
  89973. }
  89974. }
  89975. else {
  89976. var webVRController = gamepad;
  89977. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  89978. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  89979. _this.rightController = controller;
  89980. }
  89981. else {
  89982. _this.leftController = controller;
  89983. }
  89984. _this._tryEnableInteractionOnController(controller);
  89985. }
  89986. };
  89987. // 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
  89988. this._tryEnableInteractionOnController = function (controller) {
  89989. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  89990. _this._enableInteractionOnController(controller);
  89991. }
  89992. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  89993. _this._enableTeleportationOnController(controller);
  89994. }
  89995. };
  89996. this._onNewGamepadDisconnected = function (gamepad) {
  89997. if (gamepad instanceof BABYLON.WebVRController) {
  89998. if (gamepad.hand === "left" && _this.leftController != null) {
  89999. _this.leftController.dispose();
  90000. _this.leftController = null;
  90001. }
  90002. if (gamepad.hand === "right" && _this.rightController != null) {
  90003. _this.rightController.dispose();
  90004. _this.rightController = null;
  90005. }
  90006. }
  90007. };
  90008. this._workingVector = BABYLON.Vector3.Zero();
  90009. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90010. this._workingMatrix = BABYLON.Matrix.Identity();
  90011. this._scene = scene;
  90012. this._canvas = scene.getEngine().getRenderingCanvas();
  90013. // Parse options
  90014. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90015. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90016. }
  90017. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90018. webVROptions.createDeviceOrientationCamera = true;
  90019. }
  90020. if (webVROptions.laserToggle === undefined) {
  90021. webVROptions.laserToggle = true;
  90022. }
  90023. if (webVROptions.defaultHeight === undefined) {
  90024. webVROptions.defaultHeight = 1.7;
  90025. }
  90026. if (webVROptions.useCustomVRButton) {
  90027. this._useCustomVRButton = true;
  90028. if (webVROptions.customVRButton) {
  90029. this._btnVR = webVROptions.customVRButton;
  90030. }
  90031. }
  90032. if (webVROptions.rayLength) {
  90033. this._rayLength = webVROptions.rayLength;
  90034. }
  90035. this._defaultHeight = webVROptions.defaultHeight;
  90036. if (webVROptions.positionScale) {
  90037. this._rayLength *= webVROptions.positionScale;
  90038. this._defaultHeight *= webVROptions.positionScale;
  90039. }
  90040. // Set position
  90041. if (this._scene.activeCamera) {
  90042. this._position = this._scene.activeCamera.position.clone();
  90043. }
  90044. else {
  90045. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90046. }
  90047. // Set non-vr camera
  90048. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90049. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90050. // Copy data from existing camera
  90051. if (this._scene.activeCamera) {
  90052. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90053. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90054. // Set rotation from previous camera
  90055. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90056. var targetCamera = this._scene.activeCamera;
  90057. if (targetCamera.rotationQuaternion) {
  90058. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90059. }
  90060. else {
  90061. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90062. }
  90063. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90064. }
  90065. }
  90066. this._scene.activeCamera = this._deviceOrientationCamera;
  90067. if (this._canvas) {
  90068. this._scene.activeCamera.attachControl(this._canvas);
  90069. }
  90070. }
  90071. else {
  90072. this._existingCamera = this._scene.activeCamera;
  90073. }
  90074. // Create VR cameras
  90075. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90076. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90077. }
  90078. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90079. this._webVRCamera.useStandingMatrix();
  90080. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90081. // Create default button
  90082. if (!this._useCustomVRButton) {
  90083. this._btnVR = document.createElement("BUTTON");
  90084. this._btnVR.className = "babylonVRicon";
  90085. this._btnVR.id = "babylonVRiconbtn";
  90086. this._btnVR.title = "Click to switch to VR";
  90087. 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) }";
  90088. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90089. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90090. // css += ".babylonVRicon.vrdisplaysupported { }";
  90091. // css += ".babylonVRicon.vrdisplayready { }";
  90092. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90093. var style = document.createElement('style');
  90094. style.appendChild(document.createTextNode(css));
  90095. document.getElementsByTagName('head')[0].appendChild(style);
  90096. this.moveButtonToBottomRight();
  90097. }
  90098. // VR button click event
  90099. if (this._btnVR) {
  90100. this._btnVR.addEventListener("click", function () {
  90101. if (!_this.isInVRMode) {
  90102. _this.enterVR();
  90103. }
  90104. else {
  90105. _this.exitVR();
  90106. }
  90107. });
  90108. }
  90109. // Window events
  90110. window.addEventListener("resize", this._onResize);
  90111. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90112. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90113. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90114. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90115. // Display vr button when headset is connected
  90116. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90117. this.displayVRButton();
  90118. }
  90119. else {
  90120. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90121. if (e.vrDisplay) {
  90122. _this.displayVRButton();
  90123. }
  90124. });
  90125. }
  90126. // Exiting VR mode using 'ESC' key on desktop
  90127. this._onKeyDown = function (event) {
  90128. if (event.keyCode === 27 && _this.isInVRMode) {
  90129. _this.exitVR();
  90130. }
  90131. };
  90132. document.addEventListener("keydown", this._onKeyDown);
  90133. // Exiting VR mode double tapping the touch screen
  90134. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90135. if (_this.isInVRMode) {
  90136. _this.exitVR();
  90137. if (_this._fullscreenVRpresenting) {
  90138. _this._scene.getEngine().switchFullscreen(true);
  90139. }
  90140. }
  90141. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90142. // Listen for WebVR display changes
  90143. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90144. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90145. this._onVRRequestPresentStart = function () {
  90146. _this._webVRrequesting = true;
  90147. _this.updateButtonVisibility();
  90148. };
  90149. this._onVRRequestPresentComplete = function (success) {
  90150. _this._webVRrequesting = false;
  90151. _this.updateButtonVisibility();
  90152. };
  90153. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90154. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90155. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90156. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90157. scene.onDisposeObservable.add(function () {
  90158. _this.dispose();
  90159. });
  90160. // Gamepad connection events
  90161. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90162. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90163. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90164. this.updateButtonVisibility();
  90165. //create easing functions
  90166. this._circleEase = new BABYLON.CircleEase();
  90167. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90168. if (this.webVROptions.floorMeshes) {
  90169. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90170. }
  90171. }
  90172. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90173. /** Return this.onEnteringVRObservable
  90174. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90175. */
  90176. get: function () {
  90177. return this.onEnteringVRObservable;
  90178. },
  90179. enumerable: true,
  90180. configurable: true
  90181. });
  90182. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90183. /** Return this.onExitingVRObservable
  90184. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90185. */
  90186. get: function () {
  90187. return this.onExitingVRObservable;
  90188. },
  90189. enumerable: true,
  90190. configurable: true
  90191. });
  90192. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90193. /** Return this.onControllerMeshLoadedObservable
  90194. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90195. */
  90196. get: function () {
  90197. return this.onControllerMeshLoadedObservable;
  90198. },
  90199. enumerable: true,
  90200. configurable: true
  90201. });
  90202. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90203. /**
  90204. * The mesh used to display where the user is going to teleport.
  90205. */
  90206. get: function () {
  90207. return this._teleportationTarget;
  90208. },
  90209. /**
  90210. * Sets the mesh to be used to display where the user is going to teleport.
  90211. */
  90212. set: function (value) {
  90213. if (value) {
  90214. value.name = "teleportationTarget";
  90215. this._isDefaultTeleportationTarget = false;
  90216. this._teleportationTarget = value;
  90217. }
  90218. },
  90219. enumerable: true,
  90220. configurable: true
  90221. });
  90222. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90223. /**
  90224. * The mesh used to display where the user is selecting,
  90225. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90226. * See http://doc.babylonjs.com/resources/baking_transformations
  90227. */
  90228. get: function () {
  90229. return this._cameraGazer._gazeTracker;
  90230. },
  90231. set: function (value) {
  90232. if (value) {
  90233. this._cameraGazer._gazeTracker = value;
  90234. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90235. this._cameraGazer._gazeTracker.isPickable = false;
  90236. this._cameraGazer._gazeTracker.isVisible = false;
  90237. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90238. if (this.leftController) {
  90239. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90240. }
  90241. if (this.rightController) {
  90242. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90243. }
  90244. }
  90245. },
  90246. enumerable: true,
  90247. configurable: true
  90248. });
  90249. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90250. /**
  90251. * If the ray of the gaze should be displayed.
  90252. */
  90253. get: function () {
  90254. return this._displayGaze;
  90255. },
  90256. /**
  90257. * Sets if the ray of the gaze should be displayed.
  90258. */
  90259. set: function (value) {
  90260. this._displayGaze = value;
  90261. if (!value) {
  90262. this._cameraGazer._gazeTracker.isVisible = false;
  90263. if (this.leftController) {
  90264. this.leftController._gazeTracker.isVisible = false;
  90265. }
  90266. if (this.rightController) {
  90267. this.rightController._gazeTracker.isVisible = false;
  90268. }
  90269. }
  90270. },
  90271. enumerable: true,
  90272. configurable: true
  90273. });
  90274. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90275. /**
  90276. * If the ray of the LaserPointer should be displayed.
  90277. */
  90278. get: function () {
  90279. return this._displayLaserPointer;
  90280. },
  90281. /**
  90282. * Sets if the ray of the LaserPointer should be displayed.
  90283. */
  90284. set: function (value) {
  90285. this._displayLaserPointer = value;
  90286. if (!value) {
  90287. if (this.rightController) {
  90288. this.rightController._deactivatePointer();
  90289. this.rightController._gazeTracker.isVisible = false;
  90290. }
  90291. if (this.leftController) {
  90292. this.leftController._deactivatePointer();
  90293. this.leftController._gazeTracker.isVisible = false;
  90294. }
  90295. }
  90296. else {
  90297. if (this.rightController) {
  90298. this.rightController._activatePointer();
  90299. }
  90300. if (this.leftController) {
  90301. this.leftController._activatePointer();
  90302. }
  90303. }
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90309. /**
  90310. * The deviceOrientationCamera used as the camera when not in VR.
  90311. */
  90312. get: function () {
  90313. return this._deviceOrientationCamera;
  90314. },
  90315. enumerable: true,
  90316. configurable: true
  90317. });
  90318. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90319. /**
  90320. * Based on the current WebVR support, returns the current VR camera used.
  90321. */
  90322. get: function () {
  90323. if (this._webVRready) {
  90324. return this._webVRCamera;
  90325. }
  90326. else {
  90327. return this._scene.activeCamera;
  90328. }
  90329. },
  90330. enumerable: true,
  90331. configurable: true
  90332. });
  90333. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90334. /**
  90335. * The webVRCamera which is used when in VR.
  90336. */
  90337. get: function () {
  90338. return this._webVRCamera;
  90339. },
  90340. enumerable: true,
  90341. configurable: true
  90342. });
  90343. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90344. /**
  90345. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90346. */
  90347. get: function () {
  90348. return this._vrDeviceOrientationCamera;
  90349. },
  90350. enumerable: true,
  90351. configurable: true
  90352. });
  90353. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90354. get: function () {
  90355. var result = this._cameraGazer._teleportationRequestInitiated
  90356. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90357. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90358. return result;
  90359. },
  90360. enumerable: true,
  90361. configurable: true
  90362. });
  90363. // Raised when one of the controller has loaded successfully its associated default mesh
  90364. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90365. if (this.leftController && this.leftController.webVRController == webVRController) {
  90366. if (webVRController.mesh) {
  90367. this.leftController._setLaserPointerParent(webVRController.mesh);
  90368. }
  90369. }
  90370. if (this.rightController && this.rightController.webVRController == webVRController) {
  90371. if (webVRController.mesh) {
  90372. this.rightController._setLaserPointerParent(webVRController.mesh);
  90373. }
  90374. }
  90375. try {
  90376. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90377. }
  90378. catch (err) {
  90379. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90380. }
  90381. };
  90382. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90383. /**
  90384. * Gets a value indicating if we are currently in VR mode.
  90385. */
  90386. get: function () {
  90387. return this._webVRpresenting || this._fullscreenVRpresenting;
  90388. },
  90389. enumerable: true,
  90390. configurable: true
  90391. });
  90392. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90393. var vrDisplay = this._scene.getEngine().getVRDevice();
  90394. if (vrDisplay) {
  90395. var wasPresenting = this._webVRpresenting;
  90396. // A VR display is connected
  90397. this._webVRpresenting = vrDisplay.isPresenting;
  90398. if (wasPresenting && !this._webVRpresenting)
  90399. this.exitVR();
  90400. }
  90401. else {
  90402. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90403. }
  90404. this.updateButtonVisibility();
  90405. };
  90406. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90407. this._webVRsupported = eventArgs.vrSupported;
  90408. this._webVRready = !!eventArgs.vrDisplay;
  90409. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90410. this.updateButtonVisibility();
  90411. };
  90412. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90413. if (this._canvas && !this._useCustomVRButton) {
  90414. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90415. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90416. }
  90417. };
  90418. VRExperienceHelper.prototype.displayVRButton = function () {
  90419. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90420. document.body.appendChild(this._btnVR);
  90421. this._btnVRDisplayed = true;
  90422. }
  90423. };
  90424. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90425. if (!this._btnVR || this._useCustomVRButton) {
  90426. return;
  90427. }
  90428. this._btnVR.className = "babylonVRicon";
  90429. if (this.isInVRMode) {
  90430. this._btnVR.className += " vrdisplaypresenting";
  90431. }
  90432. else {
  90433. if (this._webVRready)
  90434. this._btnVR.className += " vrdisplayready";
  90435. if (this._webVRsupported)
  90436. this._btnVR.className += " vrdisplaysupported";
  90437. if (this._webVRrequesting)
  90438. this._btnVR.className += " vrdisplayrequesting";
  90439. }
  90440. };
  90441. /**
  90442. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90443. * Otherwise, will use the fullscreen API.
  90444. */
  90445. VRExperienceHelper.prototype.enterVR = function () {
  90446. if (this.onEnteringVRObservable) {
  90447. try {
  90448. this.onEnteringVRObservable.notifyObservers(this);
  90449. }
  90450. catch (err) {
  90451. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90452. }
  90453. }
  90454. if (this._scene.activeCamera) {
  90455. this._position = this._scene.activeCamera.position.clone();
  90456. // make sure that we return to the last active camera
  90457. this._existingCamera = this._scene.activeCamera;
  90458. }
  90459. if (this._webVRrequesting)
  90460. return;
  90461. // If WebVR is supported and a headset is connected
  90462. if (this._webVRready) {
  90463. if (!this._webVRpresenting) {
  90464. this._webVRCamera.position = this._position;
  90465. this._scene.activeCamera = this._webVRCamera;
  90466. }
  90467. }
  90468. else if (this._vrDeviceOrientationCamera) {
  90469. this._vrDeviceOrientationCamera.position = this._position;
  90470. if (this._scene.activeCamera) {
  90471. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90472. }
  90473. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90474. this._scene.getEngine().switchFullscreen(true);
  90475. this.updateButtonVisibility();
  90476. }
  90477. if (this._scene.activeCamera && this._canvas) {
  90478. this._scene.activeCamera.attachControl(this._canvas);
  90479. }
  90480. if (this._interactionsEnabled) {
  90481. this._scene.registerBeforeRender(this.beforeRender);
  90482. }
  90483. };
  90484. /**
  90485. * Attempt to exit VR, or fullscreen.
  90486. */
  90487. VRExperienceHelper.prototype.exitVR = function () {
  90488. if (this.onExitingVRObservable) {
  90489. try {
  90490. this.onExitingVRObservable.notifyObservers(this);
  90491. }
  90492. catch (err) {
  90493. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90494. }
  90495. }
  90496. if (this._webVRpresenting) {
  90497. this._scene.getEngine().disableVR();
  90498. }
  90499. if (this._scene.activeCamera) {
  90500. this._position = this._scene.activeCamera.position.clone();
  90501. }
  90502. if (this._deviceOrientationCamera) {
  90503. this._deviceOrientationCamera.position = this._position;
  90504. this._scene.activeCamera = this._deviceOrientationCamera;
  90505. if (this._canvas) {
  90506. this._scene.activeCamera.attachControl(this._canvas);
  90507. }
  90508. }
  90509. else if (this._existingCamera) {
  90510. this._existingCamera.position = this._position;
  90511. this._scene.activeCamera = this._existingCamera;
  90512. }
  90513. this.updateButtonVisibility();
  90514. if (this._interactionsEnabled) {
  90515. this._scene.unregisterBeforeRender(this.beforeRender);
  90516. }
  90517. // resize to update width and height when exiting vr exits fullscreen
  90518. this._scene.getEngine().resize();
  90519. };
  90520. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90521. /**
  90522. * The position of the vr experience helper.
  90523. */
  90524. get: function () {
  90525. return this._position;
  90526. },
  90527. /**
  90528. * Sets the position of the vr experience helper.
  90529. */
  90530. set: function (value) {
  90531. this._position = value;
  90532. if (this._scene.activeCamera) {
  90533. this._scene.activeCamera.position = value;
  90534. }
  90535. },
  90536. enumerable: true,
  90537. configurable: true
  90538. });
  90539. /**
  90540. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90541. */
  90542. VRExperienceHelper.prototype.enableInteractions = function () {
  90543. var _this = this;
  90544. if (!this._interactionsEnabled) {
  90545. this._interactionsRequested = true;
  90546. if (this.leftController) {
  90547. this._enableInteractionOnController(this.leftController);
  90548. }
  90549. if (this.rightController) {
  90550. this._enableInteractionOnController(this.rightController);
  90551. }
  90552. this.raySelectionPredicate = function (mesh) {
  90553. return mesh.isVisible;
  90554. };
  90555. this.meshSelectionPredicate = function (mesh) {
  90556. return true;
  90557. };
  90558. this._raySelectionPredicate = function (mesh) {
  90559. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90560. && mesh.name.indexOf("teleportationTarget") === -1
  90561. && mesh.name.indexOf("torusTeleportation") === -1
  90562. && mesh.name.indexOf("laserPointer") === -1)) {
  90563. return _this.raySelectionPredicate(mesh);
  90564. }
  90565. return false;
  90566. };
  90567. this._interactionsEnabled = true;
  90568. }
  90569. };
  90570. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90571. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90572. if (this._floorMeshesCollection[i].id === mesh.id) {
  90573. return true;
  90574. }
  90575. }
  90576. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90577. return true;
  90578. }
  90579. return false;
  90580. };
  90581. /**
  90582. * Adds a floor mesh to be used for teleportation.
  90583. * @param floorMesh the mesh to be used for teleportation.
  90584. */
  90585. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90586. if (!this._floorMeshesCollection) {
  90587. return;
  90588. }
  90589. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90590. return;
  90591. }
  90592. this._floorMeshesCollection.push(floorMesh);
  90593. };
  90594. /**
  90595. * Removes a floor mesh from being used for teleportation.
  90596. * @param floorMesh the mesh to be removed.
  90597. */
  90598. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90599. if (!this._floorMeshesCollection) {
  90600. return;
  90601. }
  90602. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90603. if (meshIndex !== -1) {
  90604. this._floorMeshesCollection.splice(meshIndex, 1);
  90605. }
  90606. };
  90607. /**
  90608. * Enables interactions and teleportation using the VR controllers and gaze.
  90609. * @param vrTeleportationOptions options to modify teleportation behavior.
  90610. */
  90611. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90612. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90613. if (!this._teleportationInitialized) {
  90614. this._teleportationRequested = true;
  90615. this.enableInteractions();
  90616. if (vrTeleportationOptions.floorMeshName) {
  90617. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90618. }
  90619. if (vrTeleportationOptions.floorMeshes) {
  90620. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90621. }
  90622. if (this.leftController != null) {
  90623. this._enableTeleportationOnController(this.leftController);
  90624. }
  90625. if (this.rightController != null) {
  90626. this._enableTeleportationOnController(this.rightController);
  90627. }
  90628. // Creates an image processing post process for the vignette not relying
  90629. // on the main scene configuration for image processing to reduce setup and spaces
  90630. // (gamma/linear) conflicts.
  90631. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90632. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90633. imageProcessingConfiguration.vignetteEnabled = true;
  90634. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90635. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90636. this._teleportationInitialized = true;
  90637. if (this._isDefaultTeleportationTarget) {
  90638. this._createTeleportationCircles();
  90639. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90640. }
  90641. }
  90642. };
  90643. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90644. var _this = this;
  90645. var controllerMesh = controller.webVRController.mesh;
  90646. if (controllerMesh) {
  90647. controller._interactionsEnabled = true;
  90648. controller._activatePointer();
  90649. if (this.webVROptions.laserToggle) {
  90650. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90651. // Enabling / disabling laserPointer
  90652. if (_this._displayLaserPointer && stateObject.value === 1) {
  90653. if (controller._activePointer) {
  90654. controller._deactivatePointer();
  90655. }
  90656. else {
  90657. controller._activatePointer();
  90658. }
  90659. if (_this.displayGaze) {
  90660. controller._gazeTracker.isVisible = controller._activePointer;
  90661. }
  90662. }
  90663. });
  90664. }
  90665. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90666. if (!controller._pointerDownOnMeshAsked) {
  90667. if (stateObject.value > _this._padSensibilityUp) {
  90668. controller._selectionPointerDown();
  90669. }
  90670. }
  90671. else if (stateObject.value < _this._padSensibilityDown) {
  90672. controller._selectionPointerUp();
  90673. }
  90674. });
  90675. }
  90676. };
  90677. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90678. // Dont teleport if another gaze already requested teleportation
  90679. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90680. return;
  90681. }
  90682. if (!gazer._teleportationRequestInitiated) {
  90683. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90684. gazer._activatePointer();
  90685. gazer._teleportationRequestInitiated = true;
  90686. }
  90687. }
  90688. else {
  90689. // Listening to the proper controller values changes to confirm teleportation
  90690. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90691. if (this._teleportActive) {
  90692. this._teleportCamera(this._haloCenter);
  90693. }
  90694. gazer._teleportationRequestInitiated = false;
  90695. }
  90696. }
  90697. };
  90698. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90699. // Only rotate when user is not currently selecting a teleportation location
  90700. if (gazer._teleportationRequestInitiated) {
  90701. return;
  90702. }
  90703. if (!gazer._rotationLeftAsked) {
  90704. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90705. gazer._rotationLeftAsked = true;
  90706. if (this._rotationAllowed) {
  90707. this._rotateCamera(false);
  90708. }
  90709. }
  90710. }
  90711. else {
  90712. if (stateObject.x > -this._padSensibilityDown) {
  90713. gazer._rotationLeftAsked = false;
  90714. }
  90715. }
  90716. if (!gazer._rotationRightAsked) {
  90717. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90718. gazer._rotationRightAsked = true;
  90719. if (this._rotationAllowed) {
  90720. this._rotateCamera(true);
  90721. }
  90722. }
  90723. }
  90724. else {
  90725. if (stateObject.x < this._padSensibilityDown) {
  90726. gazer._rotationRightAsked = false;
  90727. }
  90728. }
  90729. };
  90730. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90731. // Only teleport backwards when user is not currently selecting a teleportation location
  90732. if (gazer._teleportationRequestInitiated) {
  90733. return;
  90734. }
  90735. // Teleport backwards
  90736. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90737. if (!gazer._teleportationBackRequestInitiated) {
  90738. if (!this.currentVRCamera) {
  90739. return;
  90740. }
  90741. // Get rotation and position of the current camera
  90742. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90743. var position = this.currentVRCamera.position;
  90744. // If the camera has device position, use that instead
  90745. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90746. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90747. position = this.currentVRCamera.devicePosition;
  90748. }
  90749. // Get matrix with only the y rotation of the device rotation
  90750. rotation.toEulerAnglesToRef(this._workingVector);
  90751. this._workingVector.z = 0;
  90752. this._workingVector.x = 0;
  90753. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90754. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90755. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90756. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90757. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90758. var ray = new BABYLON.Ray(position, this._workingVector);
  90759. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90760. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90761. this._teleportCamera(hit.pickedPoint);
  90762. }
  90763. gazer._teleportationBackRequestInitiated = true;
  90764. }
  90765. }
  90766. else {
  90767. gazer._teleportationBackRequestInitiated = false;
  90768. }
  90769. };
  90770. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90771. var _this = this;
  90772. var controllerMesh = controller.webVRController.mesh;
  90773. if (controllerMesh) {
  90774. if (!controller._interactionsEnabled) {
  90775. this._enableInteractionOnController(controller);
  90776. }
  90777. controller._interactionsEnabled = true;
  90778. controller._teleportationEnabled = true;
  90779. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90780. controller._dpadPressed = false;
  90781. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90782. controller._dpadPressed = stateObject.pressed;
  90783. if (!controller._dpadPressed) {
  90784. controller._rotationLeftAsked = false;
  90785. controller._rotationRightAsked = false;
  90786. controller._teleportationBackRequestInitiated = false;
  90787. }
  90788. });
  90789. }
  90790. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90791. if (_this.teleportationEnabled) {
  90792. _this._checkTeleportBackwards(stateObject, controller);
  90793. _this._checkTeleportWithRay(stateObject, controller);
  90794. }
  90795. _this._checkRotate(stateObject, controller);
  90796. });
  90797. }
  90798. };
  90799. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90800. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90801. this._teleportationTarget.isPickable = false;
  90802. var length = 512;
  90803. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90804. dynamicTexture.hasAlpha = true;
  90805. var context = dynamicTexture.getContext();
  90806. var centerX = length / 2;
  90807. var centerY = length / 2;
  90808. var radius = 200;
  90809. context.beginPath();
  90810. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90811. context.fillStyle = this._teleportationFillColor;
  90812. context.fill();
  90813. context.lineWidth = 10;
  90814. context.strokeStyle = this._teleportationBorderColor;
  90815. context.stroke();
  90816. context.closePath();
  90817. dynamicTexture.update();
  90818. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90819. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90820. this._teleportationTarget.material = teleportationCircleMaterial;
  90821. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90822. torus.isPickable = false;
  90823. torus.parent = this._teleportationTarget;
  90824. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90825. var keys = [];
  90826. keys.push({
  90827. frame: 0,
  90828. value: 0
  90829. });
  90830. keys.push({
  90831. frame: 30,
  90832. value: 0.4
  90833. });
  90834. keys.push({
  90835. frame: 60,
  90836. value: 0
  90837. });
  90838. animationInnerCircle.setKeys(keys);
  90839. var easingFunction = new BABYLON.SineEase();
  90840. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90841. animationInnerCircle.setEasingFunction(easingFunction);
  90842. torus.animations = [];
  90843. torus.animations.push(animationInnerCircle);
  90844. this._scene.beginAnimation(torus, 0, 60, true);
  90845. this._hideTeleportationTarget();
  90846. };
  90847. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90848. this._teleportActive = true;
  90849. if (this._teleportationInitialized) {
  90850. this._teleportationTarget.isVisible = true;
  90851. if (this._isDefaultTeleportationTarget) {
  90852. this._teleportationTarget.getChildren()[0].isVisible = true;
  90853. }
  90854. }
  90855. };
  90856. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90857. this._teleportActive = false;
  90858. if (this._teleportationInitialized) {
  90859. this._teleportationTarget.isVisible = false;
  90860. if (this._isDefaultTeleportationTarget) {
  90861. this._teleportationTarget.getChildren()[0].isVisible = false;
  90862. }
  90863. }
  90864. };
  90865. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90866. var _this = this;
  90867. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90868. return;
  90869. }
  90870. if (right) {
  90871. this._rotationAngle++;
  90872. }
  90873. else {
  90874. this._rotationAngle--;
  90875. }
  90876. this.currentVRCamera.animations = [];
  90877. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90878. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90879. var animationRotationKeys = [];
  90880. animationRotationKeys.push({
  90881. frame: 0,
  90882. value: this.currentVRCamera.rotationQuaternion
  90883. });
  90884. animationRotationKeys.push({
  90885. frame: 6,
  90886. value: target
  90887. });
  90888. animationRotation.setKeys(animationRotationKeys);
  90889. animationRotation.setEasingFunction(this._circleEase);
  90890. this.currentVRCamera.animations.push(animationRotation);
  90891. this._postProcessMove.animations = [];
  90892. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90893. var vignetteWeightKeys = [];
  90894. vignetteWeightKeys.push({
  90895. frame: 0,
  90896. value: 0
  90897. });
  90898. vignetteWeightKeys.push({
  90899. frame: 3,
  90900. value: 4
  90901. });
  90902. vignetteWeightKeys.push({
  90903. frame: 6,
  90904. value: 0
  90905. });
  90906. animationPP.setKeys(vignetteWeightKeys);
  90907. animationPP.setEasingFunction(this._circleEase);
  90908. this._postProcessMove.animations.push(animationPP);
  90909. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90910. var vignetteStretchKeys = [];
  90911. vignetteStretchKeys.push({
  90912. frame: 0,
  90913. value: 0
  90914. });
  90915. vignetteStretchKeys.push({
  90916. frame: 3,
  90917. value: 10
  90918. });
  90919. vignetteStretchKeys.push({
  90920. frame: 6,
  90921. value: 0
  90922. });
  90923. animationPP2.setKeys(vignetteStretchKeys);
  90924. animationPP2.setEasingFunction(this._circleEase);
  90925. this._postProcessMove.animations.push(animationPP2);
  90926. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90927. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90928. this._postProcessMove.samples = 4;
  90929. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90930. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90931. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90932. });
  90933. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90934. };
  90935. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90936. if (hit.pickedPoint) {
  90937. if (gazer._teleportationRequestInitiated) {
  90938. this._displayTeleportationTarget();
  90939. this._haloCenter.copyFrom(hit.pickedPoint);
  90940. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90941. }
  90942. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90943. if (pickNormal) {
  90944. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90945. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90946. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90947. }
  90948. this._teleportationTarget.position.y += 0.1;
  90949. }
  90950. };
  90951. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90952. var _this = this;
  90953. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90954. return;
  90955. }
  90956. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90957. // offset of the headset from the anchor.
  90958. if (this.webVRCamera.leftCamera) {
  90959. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90960. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90961. location.subtractToRef(this._workingVector, this._workingVector);
  90962. }
  90963. else {
  90964. this._workingVector.copyFrom(location);
  90965. }
  90966. // Add height to account for user's height offset
  90967. if (this.isInVRMode) {
  90968. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90969. }
  90970. else {
  90971. this._workingVector.y += this._defaultHeight;
  90972. }
  90973. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  90974. // Create animation from the camera's position to the new location
  90975. this.currentVRCamera.animations = [];
  90976. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90977. var animationCameraTeleportationKeys = [{
  90978. frame: 0,
  90979. value: this.currentVRCamera.position
  90980. },
  90981. {
  90982. frame: 11,
  90983. value: this._workingVector
  90984. }
  90985. ];
  90986. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  90987. animationCameraTeleportation.setEasingFunction(this._circleEase);
  90988. this.currentVRCamera.animations.push(animationCameraTeleportation);
  90989. this._postProcessMove.animations = [];
  90990. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90991. var vignetteWeightKeys = [];
  90992. vignetteWeightKeys.push({
  90993. frame: 0,
  90994. value: 0
  90995. });
  90996. vignetteWeightKeys.push({
  90997. frame: 5,
  90998. value: 8
  90999. });
  91000. vignetteWeightKeys.push({
  91001. frame: 11,
  91002. value: 0
  91003. });
  91004. animationPP.setKeys(vignetteWeightKeys);
  91005. this._postProcessMove.animations.push(animationPP);
  91006. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91007. var vignetteStretchKeys = [];
  91008. vignetteStretchKeys.push({
  91009. frame: 0,
  91010. value: 0
  91011. });
  91012. vignetteStretchKeys.push({
  91013. frame: 5,
  91014. value: 10
  91015. });
  91016. vignetteStretchKeys.push({
  91017. frame: 11,
  91018. value: 0
  91019. });
  91020. animationPP2.setKeys(vignetteStretchKeys);
  91021. this._postProcessMove.animations.push(animationPP2);
  91022. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91023. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91024. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91025. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91026. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91027. });
  91028. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91029. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91030. });
  91031. this._hideTeleportationTarget();
  91032. };
  91033. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91034. if (normal) {
  91035. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91036. if (angle < Math.PI / 2) {
  91037. normal.scaleInPlace(-1);
  91038. }
  91039. }
  91040. return normal;
  91041. };
  91042. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91043. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91044. return;
  91045. }
  91046. var ray = gazer._getForwardRay(this._rayLength);
  91047. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91048. if (hit) {
  91049. // Populate the contrllers mesh that can be used for drag/drop
  91050. if (gazer._laserPointer) {
  91051. hit.originMesh = gazer._laserPointer.parent;
  91052. }
  91053. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91054. }
  91055. gazer._currentHit = hit;
  91056. // Moving the gazeTracker on the mesh face targetted
  91057. if (hit && hit.pickedPoint) {
  91058. if (this._displayGaze) {
  91059. var multiplier = 1;
  91060. gazer._gazeTracker.isVisible = true;
  91061. if (gazer._isActionableMesh) {
  91062. multiplier = 3;
  91063. }
  91064. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91065. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91066. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91067. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91068. // To avoid z-fighting
  91069. var deltaFighting = 0.002;
  91070. if (pickNormal) {
  91071. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91072. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91073. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91074. }
  91075. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91076. if (gazer._gazeTracker.position.x < 0) {
  91077. gazer._gazeTracker.position.x += deltaFighting;
  91078. }
  91079. else {
  91080. gazer._gazeTracker.position.x -= deltaFighting;
  91081. }
  91082. if (gazer._gazeTracker.position.y < 0) {
  91083. gazer._gazeTracker.position.y += deltaFighting;
  91084. }
  91085. else {
  91086. gazer._gazeTracker.position.y -= deltaFighting;
  91087. }
  91088. if (gazer._gazeTracker.position.z < 0) {
  91089. gazer._gazeTracker.position.z += deltaFighting;
  91090. }
  91091. else {
  91092. gazer._gazeTracker.position.z -= deltaFighting;
  91093. }
  91094. }
  91095. // Changing the size of the laser pointer based on the distance from the targetted point
  91096. gazer._updatePointerDistance(hit.distance);
  91097. }
  91098. else {
  91099. gazer._updatePointerDistance();
  91100. gazer._gazeTracker.isVisible = false;
  91101. }
  91102. if (hit && hit.pickedMesh) {
  91103. // The object selected is the floor, we're in a teleportation scenario
  91104. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91105. // Moving the teleportation area to this targetted point
  91106. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91107. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91108. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91109. }
  91110. gazer._currentMeshSelected = null;
  91111. if (gazer._teleportationRequestInitiated) {
  91112. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91113. }
  91114. return;
  91115. }
  91116. // If not, we're in a selection scenario
  91117. //this._teleportationAllowed = false;
  91118. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91119. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91120. this.onNewMeshPicked.notifyObservers(hit);
  91121. gazer._currentMeshSelected = hit.pickedMesh;
  91122. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91123. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91124. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91125. gazer._isActionableMesh = true;
  91126. }
  91127. else {
  91128. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91129. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91130. gazer._isActionableMesh = false;
  91131. }
  91132. try {
  91133. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91134. }
  91135. catch (err) {
  91136. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91137. }
  91138. }
  91139. else {
  91140. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91141. gazer._currentMeshSelected = null;
  91142. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91143. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91144. }
  91145. }
  91146. }
  91147. else {
  91148. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91149. gazer._currentMeshSelected = null;
  91150. //this._teleportationAllowed = false;
  91151. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91152. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91153. }
  91154. };
  91155. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91156. if (mesh) {
  91157. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91158. }
  91159. };
  91160. /**
  91161. * Sets the color of the laser ray from the vr controllers.
  91162. * @param color new color for the ray.
  91163. */
  91164. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91165. if (this.leftController) {
  91166. this.leftController._setLaserPointerColor(color);
  91167. }
  91168. if (this.rightController) {
  91169. this.rightController._setLaserPointerColor(color);
  91170. }
  91171. };
  91172. /**
  91173. * Sets the color of the ray from the vr headsets gaze.
  91174. * @param color new color for the ray.
  91175. */
  91176. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91177. if (!this._cameraGazer._gazeTracker.material) {
  91178. return;
  91179. }
  91180. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91181. if (this.leftController) {
  91182. this.leftController._gazeTracker.material.emissiveColor = color;
  91183. }
  91184. if (this.rightController) {
  91185. this.rightController._gazeTracker.material.emissiveColor = color;
  91186. }
  91187. };
  91188. /**
  91189. * Exits VR and disposes of the vr experience helper
  91190. */
  91191. VRExperienceHelper.prototype.dispose = function () {
  91192. if (this.isInVRMode) {
  91193. this.exitVR();
  91194. }
  91195. if (this._postProcessMove) {
  91196. this._postProcessMove.dispose();
  91197. }
  91198. if (this._webVRCamera) {
  91199. this._webVRCamera.dispose();
  91200. }
  91201. if (this._vrDeviceOrientationCamera) {
  91202. this._vrDeviceOrientationCamera.dispose();
  91203. }
  91204. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91205. document.body.removeChild(this._btnVR);
  91206. }
  91207. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91208. this._deviceOrientationCamera.dispose();
  91209. }
  91210. if (this._cameraGazer) {
  91211. this._cameraGazer.dispose();
  91212. }
  91213. if (this.leftController) {
  91214. this.leftController.dispose();
  91215. }
  91216. if (this.rightController) {
  91217. this.rightController.dispose();
  91218. }
  91219. if (this._teleportationTarget) {
  91220. this._teleportationTarget.dispose();
  91221. }
  91222. this._floorMeshesCollection = [];
  91223. document.removeEventListener("keydown", this._onKeyDown);
  91224. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91225. window.removeEventListener("resize", this._onResize);
  91226. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91227. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91228. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91229. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91230. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91231. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91232. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91233. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91234. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91235. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91236. this._scene.unregisterBeforeRender(this.beforeRender);
  91237. };
  91238. /**
  91239. * Gets the name of the VRExperienceHelper class
  91240. * @returns "VRExperienceHelper"
  91241. */
  91242. VRExperienceHelper.prototype.getClassName = function () {
  91243. return "VRExperienceHelper";
  91244. };
  91245. return VRExperienceHelper;
  91246. }());
  91247. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91248. })(BABYLON || (BABYLON = {}));
  91249. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91250. // Mainly based on these 2 articles :
  91251. // 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
  91252. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91253. var BABYLON;
  91254. (function (BABYLON) {
  91255. /**
  91256. * Defines the potential axis of a Joystick
  91257. */
  91258. var JoystickAxis;
  91259. (function (JoystickAxis) {
  91260. /** X axis */
  91261. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91262. /** Y axis */
  91263. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91264. /** Z axis */
  91265. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91266. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91267. /**
  91268. * Class used to define virtual joystick (used in touch mode)
  91269. */
  91270. var VirtualJoystick = /** @class */ (function () {
  91271. /**
  91272. * Creates a new virtual joystick
  91273. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91274. */
  91275. function VirtualJoystick(leftJoystick) {
  91276. var _this = this;
  91277. if (leftJoystick) {
  91278. this._leftJoystick = true;
  91279. }
  91280. else {
  91281. this._leftJoystick = false;
  91282. }
  91283. VirtualJoystick._globalJoystickIndex++;
  91284. // By default left & right arrow keys are moving the X
  91285. // and up & down keys are moving the Y
  91286. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91287. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91288. this.reverseLeftRight = false;
  91289. this.reverseUpDown = false;
  91290. // collections of pointers
  91291. this._touches = new BABYLON.StringDictionary();
  91292. this.deltaPosition = BABYLON.Vector3.Zero();
  91293. this._joystickSensibility = 25;
  91294. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91295. this._onResize = function (evt) {
  91296. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91297. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91298. if (VirtualJoystick.vjCanvas) {
  91299. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91300. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91301. }
  91302. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91303. };
  91304. // injecting a canvas element on top of the canvas 3D game
  91305. if (!VirtualJoystick.vjCanvas) {
  91306. window.addEventListener("resize", this._onResize, false);
  91307. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91308. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91309. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91310. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91311. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91312. VirtualJoystick.vjCanvas.style.width = "100%";
  91313. VirtualJoystick.vjCanvas.style.height = "100%";
  91314. VirtualJoystick.vjCanvas.style.position = "absolute";
  91315. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91316. VirtualJoystick.vjCanvas.style.top = "0px";
  91317. VirtualJoystick.vjCanvas.style.left = "0px";
  91318. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91319. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91320. // Support for jQuery PEP polyfill
  91321. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91322. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91323. if (!context) {
  91324. throw new Error("Unable to create canvas for virtual joystick");
  91325. }
  91326. VirtualJoystick.vjCanvasContext = context;
  91327. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91328. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91329. document.body.appendChild(VirtualJoystick.vjCanvas);
  91330. }
  91331. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91332. this.pressed = false;
  91333. // default joystick color
  91334. this._joystickColor = "cyan";
  91335. this._joystickPointerID = -1;
  91336. // current joystick position
  91337. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91338. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91339. // origin joystick position
  91340. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91341. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91342. this._onPointerDownHandlerRef = function (evt) {
  91343. _this._onPointerDown(evt);
  91344. };
  91345. this._onPointerMoveHandlerRef = function (evt) {
  91346. _this._onPointerMove(evt);
  91347. };
  91348. this._onPointerUpHandlerRef = function (evt) {
  91349. _this._onPointerUp(evt);
  91350. };
  91351. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91352. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91353. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91354. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91355. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91356. evt.preventDefault(); // Disables system menu
  91357. }, false);
  91358. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91359. }
  91360. /**
  91361. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91362. * @param newJoystickSensibility defines the new sensibility
  91363. */
  91364. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91365. this._joystickSensibility = newJoystickSensibility;
  91366. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91367. };
  91368. VirtualJoystick.prototype._onPointerDown = function (e) {
  91369. var positionOnScreenCondition;
  91370. e.preventDefault();
  91371. if (this._leftJoystick === true) {
  91372. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91373. }
  91374. else {
  91375. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91376. }
  91377. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91378. // First contact will be dedicated to the virtual joystick
  91379. this._joystickPointerID = e.pointerId;
  91380. this._joystickPointerStartPos.x = e.clientX;
  91381. this._joystickPointerStartPos.y = e.clientY;
  91382. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91383. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91384. this._deltaJoystickVector.x = 0;
  91385. this._deltaJoystickVector.y = 0;
  91386. this.pressed = true;
  91387. this._touches.add(e.pointerId.toString(), e);
  91388. }
  91389. else {
  91390. // You can only trigger the action buttons with a joystick declared
  91391. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91392. this._action();
  91393. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91394. }
  91395. }
  91396. };
  91397. VirtualJoystick.prototype._onPointerMove = function (e) {
  91398. // If the current pointer is the one associated to the joystick (first touch contact)
  91399. if (this._joystickPointerID == e.pointerId) {
  91400. this._joystickPointerPos.x = e.clientX;
  91401. this._joystickPointerPos.y = e.clientY;
  91402. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91403. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91404. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91405. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91406. switch (this._axisTargetedByLeftAndRight) {
  91407. case JoystickAxis.X:
  91408. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91409. break;
  91410. case JoystickAxis.Y:
  91411. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91412. break;
  91413. case JoystickAxis.Z:
  91414. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91415. break;
  91416. }
  91417. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91418. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91419. switch (this._axisTargetedByUpAndDown) {
  91420. case JoystickAxis.X:
  91421. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91422. break;
  91423. case JoystickAxis.Y:
  91424. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91425. break;
  91426. case JoystickAxis.Z:
  91427. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91428. break;
  91429. }
  91430. }
  91431. else {
  91432. var data = this._touches.get(e.pointerId.toString());
  91433. if (data) {
  91434. data.x = e.clientX;
  91435. data.y = e.clientY;
  91436. }
  91437. }
  91438. };
  91439. VirtualJoystick.prototype._onPointerUp = function (e) {
  91440. if (this._joystickPointerID == e.pointerId) {
  91441. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91442. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91443. this._joystickPointerID = -1;
  91444. this.pressed = false;
  91445. }
  91446. else {
  91447. var touch = this._touches.get(e.pointerId.toString());
  91448. if (touch) {
  91449. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91450. }
  91451. }
  91452. this._deltaJoystickVector.x = 0;
  91453. this._deltaJoystickVector.y = 0;
  91454. this._touches.remove(e.pointerId.toString());
  91455. };
  91456. /**
  91457. * Change the color of the virtual joystick
  91458. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91459. */
  91460. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91461. this._joystickColor = newColor;
  91462. };
  91463. /**
  91464. * Defines a callback to call when the joystick is touched
  91465. * @param action defines the callback
  91466. */
  91467. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91468. this._action = action;
  91469. };
  91470. /**
  91471. * Defines which axis you'd like to control for left & right
  91472. * @param axis defines the axis to use
  91473. */
  91474. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91475. switch (axis) {
  91476. case JoystickAxis.X:
  91477. case JoystickAxis.Y:
  91478. case JoystickAxis.Z:
  91479. this._axisTargetedByLeftAndRight = axis;
  91480. break;
  91481. default:
  91482. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91483. break;
  91484. }
  91485. };
  91486. /**
  91487. * Defines which axis you'd like to control for up & down
  91488. * @param axis defines the axis to use
  91489. */
  91490. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91491. switch (axis) {
  91492. case JoystickAxis.X:
  91493. case JoystickAxis.Y:
  91494. case JoystickAxis.Z:
  91495. this._axisTargetedByUpAndDown = axis;
  91496. break;
  91497. default:
  91498. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91499. break;
  91500. }
  91501. };
  91502. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91503. var _this = this;
  91504. if (this.pressed) {
  91505. this._touches.forEach(function (key, touch) {
  91506. if (touch.pointerId === _this._joystickPointerID) {
  91507. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91508. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91509. VirtualJoystick.vjCanvasContext.beginPath();
  91510. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91511. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91512. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91513. VirtualJoystick.vjCanvasContext.stroke();
  91514. VirtualJoystick.vjCanvasContext.closePath();
  91515. VirtualJoystick.vjCanvasContext.beginPath();
  91516. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91517. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91518. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91519. VirtualJoystick.vjCanvasContext.stroke();
  91520. VirtualJoystick.vjCanvasContext.closePath();
  91521. VirtualJoystick.vjCanvasContext.beginPath();
  91522. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91523. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91524. VirtualJoystick.vjCanvasContext.stroke();
  91525. VirtualJoystick.vjCanvasContext.closePath();
  91526. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91527. }
  91528. else {
  91529. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91530. VirtualJoystick.vjCanvasContext.beginPath();
  91531. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91532. VirtualJoystick.vjCanvasContext.beginPath();
  91533. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91534. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91535. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91536. VirtualJoystick.vjCanvasContext.stroke();
  91537. VirtualJoystick.vjCanvasContext.closePath();
  91538. touch.prevX = touch.x;
  91539. touch.prevY = touch.y;
  91540. }
  91541. ;
  91542. });
  91543. }
  91544. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91545. };
  91546. /**
  91547. * Release internal HTML canvas
  91548. */
  91549. VirtualJoystick.prototype.releaseCanvas = function () {
  91550. if (VirtualJoystick.vjCanvas) {
  91551. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91552. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91553. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91554. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91555. window.removeEventListener("resize", this._onResize);
  91556. document.body.removeChild(VirtualJoystick.vjCanvas);
  91557. VirtualJoystick.vjCanvas = null;
  91558. }
  91559. };
  91560. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91561. VirtualJoystick._globalJoystickIndex = 0;
  91562. return VirtualJoystick;
  91563. }());
  91564. BABYLON.VirtualJoystick = VirtualJoystick;
  91565. })(BABYLON || (BABYLON = {}));
  91566. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91567. var BABYLON;
  91568. (function (BABYLON) {
  91569. // We're mainly based on the logic defined into the FreeCamera code
  91570. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91571. __extends(VirtualJoysticksCamera, _super);
  91572. function VirtualJoysticksCamera(name, position, scene) {
  91573. var _this = _super.call(this, name, position, scene) || this;
  91574. _this.inputs.addVirtualJoystick();
  91575. return _this;
  91576. }
  91577. VirtualJoysticksCamera.prototype.getClassName = function () {
  91578. return "VirtualJoysticksCamera";
  91579. };
  91580. return VirtualJoysticksCamera;
  91581. }(BABYLON.FreeCamera));
  91582. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91583. })(BABYLON || (BABYLON = {}));
  91584. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91585. var BABYLON;
  91586. (function (BABYLON) {
  91587. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91588. function FreeCameraVirtualJoystickInput() {
  91589. }
  91590. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91591. return this._leftjoystick;
  91592. };
  91593. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91594. return this._rightjoystick;
  91595. };
  91596. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91597. if (this._leftjoystick) {
  91598. var camera = this.camera;
  91599. var speed = camera._computeLocalCameraSpeed() * 50;
  91600. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91601. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91602. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91603. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91604. if (!this._leftjoystick.pressed) {
  91605. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91606. }
  91607. if (!this._rightjoystick.pressed) {
  91608. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91609. }
  91610. }
  91611. };
  91612. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91613. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91614. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91615. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91616. this._leftjoystick.setJoystickSensibility(0.15);
  91617. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91618. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91619. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91620. this._rightjoystick.reverseUpDown = true;
  91621. this._rightjoystick.setJoystickSensibility(0.05);
  91622. this._rightjoystick.setJoystickColor("yellow");
  91623. };
  91624. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91625. this._leftjoystick.releaseCanvas();
  91626. this._rightjoystick.releaseCanvas();
  91627. };
  91628. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91629. return "FreeCameraVirtualJoystickInput";
  91630. };
  91631. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91632. return "virtualJoystick";
  91633. };
  91634. return FreeCameraVirtualJoystickInput;
  91635. }());
  91636. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91637. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91638. })(BABYLON || (BABYLON = {}));
  91639. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91640. var BABYLON;
  91641. (function (BABYLON) {
  91642. var SimplificationSettings = /** @class */ (function () {
  91643. function SimplificationSettings(quality, distance, optimizeMesh) {
  91644. this.quality = quality;
  91645. this.distance = distance;
  91646. this.optimizeMesh = optimizeMesh;
  91647. }
  91648. return SimplificationSettings;
  91649. }());
  91650. BABYLON.SimplificationSettings = SimplificationSettings;
  91651. var SimplificationQueue = /** @class */ (function () {
  91652. function SimplificationQueue() {
  91653. this.running = false;
  91654. this._simplificationArray = [];
  91655. }
  91656. SimplificationQueue.prototype.addTask = function (task) {
  91657. this._simplificationArray.push(task);
  91658. };
  91659. SimplificationQueue.prototype.executeNext = function () {
  91660. var task = this._simplificationArray.pop();
  91661. if (task) {
  91662. this.running = true;
  91663. this.runSimplification(task);
  91664. }
  91665. else {
  91666. this.running = false;
  91667. }
  91668. };
  91669. SimplificationQueue.prototype.runSimplification = function (task) {
  91670. var _this = this;
  91671. if (task.parallelProcessing) {
  91672. //parallel simplifier
  91673. task.settings.forEach(function (setting) {
  91674. var simplifier = _this.getSimplifier(task);
  91675. simplifier.simplify(setting, function (newMesh) {
  91676. task.mesh.addLODLevel(setting.distance, newMesh);
  91677. newMesh.isVisible = true;
  91678. //check if it is the last
  91679. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91680. //all done, run the success callback.
  91681. task.successCallback();
  91682. }
  91683. _this.executeNext();
  91684. });
  91685. });
  91686. }
  91687. else {
  91688. //single simplifier.
  91689. var simplifier = this.getSimplifier(task);
  91690. var runDecimation = function (setting, callback) {
  91691. simplifier.simplify(setting, function (newMesh) {
  91692. task.mesh.addLODLevel(setting.distance, newMesh);
  91693. newMesh.isVisible = true;
  91694. //run the next quality level
  91695. callback();
  91696. });
  91697. };
  91698. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91699. runDecimation(task.settings[loop.index], function () {
  91700. loop.executeNext();
  91701. });
  91702. }, function () {
  91703. //execution ended, run the success callback.
  91704. if (task.successCallback) {
  91705. task.successCallback();
  91706. }
  91707. _this.executeNext();
  91708. });
  91709. }
  91710. };
  91711. SimplificationQueue.prototype.getSimplifier = function (task) {
  91712. switch (task.simplificationType) {
  91713. case SimplificationType.QUADRATIC:
  91714. default:
  91715. return new QuadraticErrorSimplification(task.mesh);
  91716. }
  91717. };
  91718. return SimplificationQueue;
  91719. }());
  91720. BABYLON.SimplificationQueue = SimplificationQueue;
  91721. /**
  91722. * The implemented types of simplification
  91723. * At the moment only Quadratic Error Decimation is implemented
  91724. */
  91725. var SimplificationType;
  91726. (function (SimplificationType) {
  91727. /** Quadratic error decimation */
  91728. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91729. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91730. var DecimationTriangle = /** @class */ (function () {
  91731. function DecimationTriangle(vertices) {
  91732. this.vertices = vertices;
  91733. this.error = new Array(4);
  91734. this.deleted = false;
  91735. this.isDirty = false;
  91736. this.deletePending = false;
  91737. this.borderFactor = 0;
  91738. }
  91739. return DecimationTriangle;
  91740. }());
  91741. BABYLON.DecimationTriangle = DecimationTriangle;
  91742. var DecimationVertex = /** @class */ (function () {
  91743. function DecimationVertex(position, id) {
  91744. this.position = position;
  91745. this.id = id;
  91746. this.isBorder = true;
  91747. this.q = new QuadraticMatrix();
  91748. this.triangleCount = 0;
  91749. this.triangleStart = 0;
  91750. this.originalOffsets = [];
  91751. }
  91752. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91753. this.position.copyFrom(newPosition);
  91754. };
  91755. return DecimationVertex;
  91756. }());
  91757. BABYLON.DecimationVertex = DecimationVertex;
  91758. var QuadraticMatrix = /** @class */ (function () {
  91759. function QuadraticMatrix(data) {
  91760. this.data = new Array(10);
  91761. for (var i = 0; i < 10; ++i) {
  91762. if (data && data[i]) {
  91763. this.data[i] = data[i];
  91764. }
  91765. else {
  91766. this.data[i] = 0;
  91767. }
  91768. }
  91769. }
  91770. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91771. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91772. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91773. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91774. return det;
  91775. };
  91776. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91777. for (var i = 0; i < 10; ++i) {
  91778. this.data[i] += matrix.data[i];
  91779. }
  91780. };
  91781. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91782. for (var i = 0; i < 10; ++i) {
  91783. this.data[i] += data[i];
  91784. }
  91785. };
  91786. QuadraticMatrix.prototype.add = function (matrix) {
  91787. var m = new QuadraticMatrix();
  91788. for (var i = 0; i < 10; ++i) {
  91789. m.data[i] = this.data[i] + matrix.data[i];
  91790. }
  91791. return m;
  91792. };
  91793. QuadraticMatrix.FromData = function (a, b, c, d) {
  91794. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91795. };
  91796. //returning an array to avoid garbage collection
  91797. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91798. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91799. };
  91800. return QuadraticMatrix;
  91801. }());
  91802. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91803. var Reference = /** @class */ (function () {
  91804. function Reference(vertexId, triangleId) {
  91805. this.vertexId = vertexId;
  91806. this.triangleId = triangleId;
  91807. }
  91808. return Reference;
  91809. }());
  91810. BABYLON.Reference = Reference;
  91811. /**
  91812. * An implementation of the Quadratic Error simplification algorithm.
  91813. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91814. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91815. * @author RaananW
  91816. */
  91817. var QuadraticErrorSimplification = /** @class */ (function () {
  91818. function QuadraticErrorSimplification(_mesh) {
  91819. this._mesh = _mesh;
  91820. this.syncIterations = 5000;
  91821. this.aggressiveness = 7;
  91822. this.decimationIterations = 100;
  91823. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91824. }
  91825. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91826. var _this = this;
  91827. this.initDecimatedMesh();
  91828. //iterating through the submeshes array, one after the other.
  91829. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91830. _this.initWithMesh(loop.index, function () {
  91831. _this.runDecimation(settings, loop.index, function () {
  91832. loop.executeNext();
  91833. });
  91834. }, settings.optimizeMesh);
  91835. }, function () {
  91836. setTimeout(function () {
  91837. successCallback(_this._reconstructedMesh);
  91838. }, 0);
  91839. });
  91840. };
  91841. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91842. var _this = this;
  91843. var targetCount = ~~(this.triangles.length * settings.quality);
  91844. var deletedTriangles = 0;
  91845. var triangleCount = this.triangles.length;
  91846. var iterationFunction = function (iteration, callback) {
  91847. setTimeout(function () {
  91848. if (iteration % 5 === 0) {
  91849. _this.updateMesh(iteration === 0);
  91850. }
  91851. for (var i = 0; i < _this.triangles.length; ++i) {
  91852. _this.triangles[i].isDirty = false;
  91853. }
  91854. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91855. var trianglesIterator = function (i) {
  91856. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91857. var t = _this.triangles[tIdx];
  91858. if (!t)
  91859. return;
  91860. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91861. return;
  91862. }
  91863. for (var j = 0; j < 3; ++j) {
  91864. if (t.error[j] < threshold) {
  91865. var deleted0 = [];
  91866. var deleted1 = [];
  91867. var v0 = t.vertices[j];
  91868. var v1 = t.vertices[(j + 1) % 3];
  91869. if (v0.isBorder || v1.isBorder)
  91870. continue;
  91871. var p = BABYLON.Vector3.Zero();
  91872. var n = BABYLON.Vector3.Zero();
  91873. var uv = BABYLON.Vector2.Zero();
  91874. var color = new BABYLON.Color4(0, 0, 0, 1);
  91875. _this.calculateError(v0, v1, p, n, uv, color);
  91876. var delTr = new Array();
  91877. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91878. continue;
  91879. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91880. continue;
  91881. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91882. continue;
  91883. var uniqueArray = new Array();
  91884. delTr.forEach(function (deletedT) {
  91885. if (uniqueArray.indexOf(deletedT) === -1) {
  91886. deletedT.deletePending = true;
  91887. uniqueArray.push(deletedT);
  91888. }
  91889. });
  91890. if (uniqueArray.length % 2 !== 0) {
  91891. continue;
  91892. }
  91893. v0.q = v1.q.add(v0.q);
  91894. v0.updatePosition(p);
  91895. var tStart = _this.references.length;
  91896. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91897. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91898. var tCount = _this.references.length - tStart;
  91899. if (tCount <= v0.triangleCount) {
  91900. if (tCount) {
  91901. for (var c = 0; c < tCount; c++) {
  91902. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91903. }
  91904. }
  91905. }
  91906. else {
  91907. v0.triangleStart = tStart;
  91908. }
  91909. v0.triangleCount = tCount;
  91910. break;
  91911. }
  91912. }
  91913. };
  91914. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91915. }, 0);
  91916. };
  91917. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91918. if (triangleCount - deletedTriangles <= targetCount)
  91919. loop.breakLoop();
  91920. else {
  91921. iterationFunction(loop.index, function () {
  91922. loop.executeNext();
  91923. });
  91924. }
  91925. }, function () {
  91926. setTimeout(function () {
  91927. //reconstruct this part of the mesh
  91928. _this.reconstructMesh(submeshIndex);
  91929. successCallback();
  91930. }, 0);
  91931. });
  91932. };
  91933. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91934. var _this = this;
  91935. this.vertices = [];
  91936. this.triangles = [];
  91937. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91938. var indices = this._mesh.getIndices();
  91939. var submesh = this._mesh.subMeshes[submeshIndex];
  91940. var findInVertices = function (positionToSearch) {
  91941. if (optimizeMesh) {
  91942. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91943. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91944. return _this.vertices[ii];
  91945. }
  91946. }
  91947. }
  91948. return null;
  91949. };
  91950. var vertexReferences = [];
  91951. var vertexInit = function (i) {
  91952. if (!positionData) {
  91953. return;
  91954. }
  91955. var offset = i + submesh.verticesStart;
  91956. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91957. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91958. vertex.originalOffsets.push(offset);
  91959. if (vertex.id === _this.vertices.length) {
  91960. _this.vertices.push(vertex);
  91961. }
  91962. vertexReferences.push(vertex.id);
  91963. };
  91964. //var totalVertices = mesh.getTotalVertices();
  91965. var totalVertices = submesh.verticesCount;
  91966. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91967. var indicesInit = function (i) {
  91968. if (!indices) {
  91969. return;
  91970. }
  91971. var offset = (submesh.indexStart / 3) + i;
  91972. var pos = (offset * 3);
  91973. var i0 = indices[pos + 0];
  91974. var i1 = indices[pos + 1];
  91975. var i2 = indices[pos + 2];
  91976. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  91977. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  91978. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  91979. var triangle = new DecimationTriangle([v0, v1, v2]);
  91980. triangle.originalOffset = pos;
  91981. _this.triangles.push(triangle);
  91982. };
  91983. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  91984. _this.init(callback);
  91985. });
  91986. });
  91987. };
  91988. QuadraticErrorSimplification.prototype.init = function (callback) {
  91989. var _this = this;
  91990. var triangleInit1 = function (i) {
  91991. var t = _this.triangles[i];
  91992. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  91993. for (var j = 0; j < 3; j++) {
  91994. 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))));
  91995. }
  91996. };
  91997. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  91998. var triangleInit2 = function (i) {
  91999. var t = _this.triangles[i];
  92000. for (var j = 0; j < 3; ++j) {
  92001. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92002. }
  92003. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92004. };
  92005. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92006. callback();
  92007. });
  92008. });
  92009. };
  92010. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92011. var newTriangles = [];
  92012. var i;
  92013. for (i = 0; i < this.vertices.length; ++i) {
  92014. this.vertices[i].triangleCount = 0;
  92015. }
  92016. var t;
  92017. var j;
  92018. for (i = 0; i < this.triangles.length; ++i) {
  92019. if (!this.triangles[i].deleted) {
  92020. t = this.triangles[i];
  92021. for (j = 0; j < 3; ++j) {
  92022. t.vertices[j].triangleCount = 1;
  92023. }
  92024. newTriangles.push(t);
  92025. }
  92026. }
  92027. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92028. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92029. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92030. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92031. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92032. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92033. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92034. var vertexCount = 0;
  92035. for (i = 0; i < this.vertices.length; ++i) {
  92036. var vertex = this.vertices[i];
  92037. vertex.id = vertexCount;
  92038. if (vertex.triangleCount) {
  92039. vertex.originalOffsets.forEach(function (originalOffset) {
  92040. if (!normalData) {
  92041. return;
  92042. }
  92043. newPositionData.push(vertex.position.x);
  92044. newPositionData.push(vertex.position.y);
  92045. newPositionData.push(vertex.position.z);
  92046. newNormalData.push(normalData[originalOffset * 3]);
  92047. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92048. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92049. if (uvs && uvs.length) {
  92050. newUVsData.push(uvs[(originalOffset * 2)]);
  92051. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92052. }
  92053. else if (colorsData && colorsData.length) {
  92054. newColorsData.push(colorsData[(originalOffset * 4)]);
  92055. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92056. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92057. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92058. }
  92059. ++vertexCount;
  92060. });
  92061. }
  92062. }
  92063. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92064. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92065. var submeshesArray = this._reconstructedMesh.subMeshes;
  92066. this._reconstructedMesh.subMeshes = [];
  92067. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92068. var originalIndices = this._mesh.getIndices();
  92069. for (i = 0; i < newTriangles.length; ++i) {
  92070. t = newTriangles[i]; //now get the new referencing point for each vertex
  92071. [0, 1, 2].forEach(function (idx) {
  92072. var id = originalIndices[t.originalOffset + idx];
  92073. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92074. if (offset < 0)
  92075. offset = 0;
  92076. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92077. });
  92078. }
  92079. //overwriting the old vertex buffers and indices.
  92080. this._reconstructedMesh.setIndices(newIndicesArray);
  92081. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92082. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92083. if (newUVsData.length > 0)
  92084. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92085. if (newColorsData.length > 0)
  92086. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92087. //create submesh
  92088. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92089. if (submeshIndex > 0) {
  92090. this._reconstructedMesh.subMeshes = [];
  92091. submeshesArray.forEach(function (submesh) {
  92092. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92093. });
  92094. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92095. }
  92096. };
  92097. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92098. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92099. this._reconstructedMesh.material = this._mesh.material;
  92100. this._reconstructedMesh.parent = this._mesh.parent;
  92101. this._reconstructedMesh.isVisible = false;
  92102. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92103. };
  92104. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92105. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92106. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92107. if (t.deleted)
  92108. continue;
  92109. var s = this.references[vertex1.triangleStart + i].vertexId;
  92110. var v1 = t.vertices[(s + 1) % 3];
  92111. var v2 = t.vertices[(s + 2) % 3];
  92112. if ((v1 === vertex2 || v2 === vertex2)) {
  92113. deletedArray[i] = true;
  92114. delTr.push(t);
  92115. continue;
  92116. }
  92117. var d1 = v1.position.subtract(point);
  92118. d1 = d1.normalize();
  92119. var d2 = v2.position.subtract(point);
  92120. d2 = d2.normalize();
  92121. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92122. return true;
  92123. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92124. deletedArray[i] = false;
  92125. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92126. return true;
  92127. }
  92128. return false;
  92129. };
  92130. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92131. var newDeleted = deletedTriangles;
  92132. for (var i = 0; i < vertex.triangleCount; ++i) {
  92133. var ref = this.references[vertex.triangleStart + i];
  92134. var t = this.triangles[ref.triangleId];
  92135. if (t.deleted)
  92136. continue;
  92137. if (deletedArray[i] && t.deletePending) {
  92138. t.deleted = true;
  92139. newDeleted++;
  92140. continue;
  92141. }
  92142. t.vertices[ref.vertexId] = origVertex;
  92143. t.isDirty = true;
  92144. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92145. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92146. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92147. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92148. this.references.push(ref);
  92149. }
  92150. return newDeleted;
  92151. };
  92152. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92153. for (var i = 0; i < this.vertices.length; ++i) {
  92154. var vCount = [];
  92155. var vId = [];
  92156. var v = this.vertices[i];
  92157. var j;
  92158. for (j = 0; j < v.triangleCount; ++j) {
  92159. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92160. for (var ii = 0; ii < 3; ii++) {
  92161. var ofs = 0;
  92162. var vv = triangle.vertices[ii];
  92163. while (ofs < vCount.length) {
  92164. if (vId[ofs] === vv.id)
  92165. break;
  92166. ++ofs;
  92167. }
  92168. if (ofs === vCount.length) {
  92169. vCount.push(1);
  92170. vId.push(vv.id);
  92171. }
  92172. else {
  92173. vCount[ofs]++;
  92174. }
  92175. }
  92176. }
  92177. for (j = 0; j < vCount.length; ++j) {
  92178. if (vCount[j] === 1) {
  92179. this.vertices[vId[j]].isBorder = true;
  92180. }
  92181. else {
  92182. this.vertices[vId[j]].isBorder = false;
  92183. }
  92184. }
  92185. }
  92186. };
  92187. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92188. if (identifyBorders === void 0) { identifyBorders = false; }
  92189. var i;
  92190. if (!identifyBorders) {
  92191. var newTrianglesVector = [];
  92192. for (i = 0; i < this.triangles.length; ++i) {
  92193. if (!this.triangles[i].deleted) {
  92194. newTrianglesVector.push(this.triangles[i]);
  92195. }
  92196. }
  92197. this.triangles = newTrianglesVector;
  92198. }
  92199. for (i = 0; i < this.vertices.length; ++i) {
  92200. this.vertices[i].triangleCount = 0;
  92201. this.vertices[i].triangleStart = 0;
  92202. }
  92203. var t;
  92204. var j;
  92205. var v;
  92206. for (i = 0; i < this.triangles.length; ++i) {
  92207. t = this.triangles[i];
  92208. for (j = 0; j < 3; ++j) {
  92209. v = t.vertices[j];
  92210. v.triangleCount++;
  92211. }
  92212. }
  92213. var tStart = 0;
  92214. for (i = 0; i < this.vertices.length; ++i) {
  92215. this.vertices[i].triangleStart = tStart;
  92216. tStart += this.vertices[i].triangleCount;
  92217. this.vertices[i].triangleCount = 0;
  92218. }
  92219. var newReferences = new Array(this.triangles.length * 3);
  92220. for (i = 0; i < this.triangles.length; ++i) {
  92221. t = this.triangles[i];
  92222. for (j = 0; j < 3; ++j) {
  92223. v = t.vertices[j];
  92224. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92225. v.triangleCount++;
  92226. }
  92227. }
  92228. this.references = newReferences;
  92229. if (identifyBorders) {
  92230. this.identifyBorder();
  92231. }
  92232. };
  92233. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92234. var x = point.x;
  92235. var y = point.y;
  92236. var z = point.z;
  92237. 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
  92238. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92239. };
  92240. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92241. var q = vertex1.q.add(vertex2.q);
  92242. var border = vertex1.isBorder && vertex2.isBorder;
  92243. var error = 0;
  92244. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92245. if (qDet !== 0 && !border) {
  92246. if (!pointResult) {
  92247. pointResult = BABYLON.Vector3.Zero();
  92248. }
  92249. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92250. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92251. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92252. error = this.vertexError(q, pointResult);
  92253. }
  92254. else {
  92255. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92256. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92257. var error1 = this.vertexError(q, vertex1.position);
  92258. var error2 = this.vertexError(q, vertex2.position);
  92259. var error3 = this.vertexError(q, p3);
  92260. error = Math.min(error1, error2, error3);
  92261. if (error === error1) {
  92262. if (pointResult) {
  92263. pointResult.copyFrom(vertex1.position);
  92264. }
  92265. }
  92266. else if (error === error2) {
  92267. if (pointResult) {
  92268. pointResult.copyFrom(vertex2.position);
  92269. }
  92270. }
  92271. else {
  92272. if (pointResult) {
  92273. pointResult.copyFrom(p3);
  92274. }
  92275. }
  92276. }
  92277. return error;
  92278. };
  92279. return QuadraticErrorSimplification;
  92280. }());
  92281. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92282. })(BABYLON || (BABYLON = {}));
  92283. //# sourceMappingURL=babylon.meshSimplification.js.map
  92284. var BABYLON;
  92285. (function (BABYLON) {
  92286. var MeshLODLevel = /** @class */ (function () {
  92287. function MeshLODLevel(distance, mesh) {
  92288. this.distance = distance;
  92289. this.mesh = mesh;
  92290. }
  92291. return MeshLODLevel;
  92292. }());
  92293. BABYLON.MeshLODLevel = MeshLODLevel;
  92294. })(BABYLON || (BABYLON = {}));
  92295. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92296. var BABYLON;
  92297. (function (BABYLON) {
  92298. /**
  92299. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92300. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92301. */
  92302. var SceneOptimization = /** @class */ (function () {
  92303. /**
  92304. * Creates the SceneOptimization object
  92305. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92306. * @param desc defines the description associated with the optimization
  92307. */
  92308. function SceneOptimization(
  92309. /**
  92310. * Defines the priority of this optimization (0 by default which means first in the list)
  92311. */
  92312. priority) {
  92313. if (priority === void 0) { priority = 0; }
  92314. this.priority = priority;
  92315. }
  92316. /**
  92317. * Gets a string describing the action executed by the current optimization
  92318. * @returns description string
  92319. */
  92320. SceneOptimization.prototype.getDescription = function () {
  92321. return "";
  92322. };
  92323. /**
  92324. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92325. * @param scene defines the current scene where to apply this optimization
  92326. * @param optimizer defines the current optimizer
  92327. * @returns true if everything that can be done was applied
  92328. */
  92329. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92330. return true;
  92331. };
  92332. ;
  92333. return SceneOptimization;
  92334. }());
  92335. BABYLON.SceneOptimization = SceneOptimization;
  92336. /**
  92337. * Defines an optimization used to reduce the size of render target textures
  92338. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92339. */
  92340. var TextureOptimization = /** @class */ (function (_super) {
  92341. __extends(TextureOptimization, _super);
  92342. /**
  92343. * Creates the TextureOptimization object
  92344. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92345. * @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
  92346. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92347. */
  92348. function TextureOptimization(
  92349. /**
  92350. * Defines the priority of this optimization (0 by default which means first in the list)
  92351. */
  92352. priority,
  92353. /**
  92354. * 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
  92355. */
  92356. maximumSize,
  92357. /**
  92358. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92359. */
  92360. step) {
  92361. if (priority === void 0) { priority = 0; }
  92362. if (maximumSize === void 0) { maximumSize = 1024; }
  92363. if (step === void 0) { step = 0.5; }
  92364. var _this = _super.call(this, priority) || this;
  92365. _this.priority = priority;
  92366. _this.maximumSize = maximumSize;
  92367. _this.step = step;
  92368. return _this;
  92369. }
  92370. /**
  92371. * Gets a string describing the action executed by the current optimization
  92372. * @returns description string
  92373. */
  92374. TextureOptimization.prototype.getDescription = function () {
  92375. return "Reducing render target texture size to " + this.maximumSize;
  92376. };
  92377. /**
  92378. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92379. * @param scene defines the current scene where to apply this optimization
  92380. * @param optimizer defines the current optimizer
  92381. * @returns true if everything that can be done was applied
  92382. */
  92383. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92384. var allDone = true;
  92385. for (var index = 0; index < scene.textures.length; index++) {
  92386. var texture = scene.textures[index];
  92387. if (!texture.canRescale || texture.getContext) {
  92388. continue;
  92389. }
  92390. var currentSize = texture.getSize();
  92391. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92392. if (maxDimension > this.maximumSize) {
  92393. texture.scale(this.step);
  92394. allDone = false;
  92395. }
  92396. }
  92397. return allDone;
  92398. };
  92399. return TextureOptimization;
  92400. }(SceneOptimization));
  92401. BABYLON.TextureOptimization = TextureOptimization;
  92402. /**
  92403. * Defines an optimization used to increase or decrease the rendering resolution
  92404. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92405. */
  92406. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92407. __extends(HardwareScalingOptimization, _super);
  92408. /**
  92409. * Creates the HardwareScalingOptimization object
  92410. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92411. * @param maximumScale defines the maximum scale to use (2 by default)
  92412. * @param step defines the step to use between two passes (0.5 by default)
  92413. */
  92414. function HardwareScalingOptimization(
  92415. /**
  92416. * Defines the priority of this optimization (0 by default which means first in the list)
  92417. */
  92418. priority,
  92419. /**
  92420. * Defines the maximum scale to use (2 by default)
  92421. */
  92422. maximumScale,
  92423. /**
  92424. * Defines the step to use between two passes (0.5 by default)
  92425. */
  92426. step) {
  92427. if (priority === void 0) { priority = 0; }
  92428. if (maximumScale === void 0) { maximumScale = 2; }
  92429. if (step === void 0) { step = 0.25; }
  92430. var _this = _super.call(this, priority) || this;
  92431. _this.priority = priority;
  92432. _this.maximumScale = maximumScale;
  92433. _this.step = step;
  92434. _this._currentScale = -1;
  92435. _this._directionOffset = 1;
  92436. return _this;
  92437. }
  92438. /**
  92439. * Gets a string describing the action executed by the current optimization
  92440. * @return description string
  92441. */
  92442. HardwareScalingOptimization.prototype.getDescription = function () {
  92443. return "Setting hardware scaling level to " + this._currentScale;
  92444. };
  92445. /**
  92446. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92447. * @param scene defines the current scene where to apply this optimization
  92448. * @param optimizer defines the current optimizer
  92449. * @returns true if everything that can be done was applied
  92450. */
  92451. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92452. if (this._currentScale === -1) {
  92453. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92454. if (this._currentScale > this.maximumScale) {
  92455. this._directionOffset = -1;
  92456. }
  92457. }
  92458. this._currentScale += this._directionOffset * this.step;
  92459. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92460. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92461. };
  92462. ;
  92463. return HardwareScalingOptimization;
  92464. }(SceneOptimization));
  92465. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92466. /**
  92467. * Defines an optimization used to remove shadows
  92468. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92469. */
  92470. var ShadowsOptimization = /** @class */ (function (_super) {
  92471. __extends(ShadowsOptimization, _super);
  92472. function ShadowsOptimization() {
  92473. return _super !== null && _super.apply(this, arguments) || this;
  92474. }
  92475. /**
  92476. * Gets a string describing the action executed by the current optimization
  92477. * @return description string
  92478. */
  92479. ShadowsOptimization.prototype.getDescription = function () {
  92480. return "Turning shadows on/off";
  92481. };
  92482. /**
  92483. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92484. * @param scene defines the current scene where to apply this optimization
  92485. * @param optimizer defines the current optimizer
  92486. * @returns true if everything that can be done was applied
  92487. */
  92488. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92489. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92490. return true;
  92491. };
  92492. ;
  92493. return ShadowsOptimization;
  92494. }(SceneOptimization));
  92495. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92496. /**
  92497. * Defines an optimization used to turn post-processes off
  92498. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92499. */
  92500. var PostProcessesOptimization = /** @class */ (function (_super) {
  92501. __extends(PostProcessesOptimization, _super);
  92502. function PostProcessesOptimization() {
  92503. return _super !== null && _super.apply(this, arguments) || this;
  92504. }
  92505. /**
  92506. * Gets a string describing the action executed by the current optimization
  92507. * @return description string
  92508. */
  92509. PostProcessesOptimization.prototype.getDescription = function () {
  92510. return "Turning post-processes on/off";
  92511. };
  92512. /**
  92513. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92514. * @param scene defines the current scene where to apply this optimization
  92515. * @param optimizer defines the current optimizer
  92516. * @returns true if everything that can be done was applied
  92517. */
  92518. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92519. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92520. return true;
  92521. };
  92522. ;
  92523. return PostProcessesOptimization;
  92524. }(SceneOptimization));
  92525. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92526. /**
  92527. * Defines an optimization used to turn lens flares off
  92528. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92529. */
  92530. var LensFlaresOptimization = /** @class */ (function (_super) {
  92531. __extends(LensFlaresOptimization, _super);
  92532. function LensFlaresOptimization() {
  92533. return _super !== null && _super.apply(this, arguments) || this;
  92534. }
  92535. /**
  92536. * Gets a string describing the action executed by the current optimization
  92537. * @return description string
  92538. */
  92539. LensFlaresOptimization.prototype.getDescription = function () {
  92540. return "Turning lens flares on/off";
  92541. };
  92542. /**
  92543. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92544. * @param scene defines the current scene where to apply this optimization
  92545. * @param optimizer defines the current optimizer
  92546. * @returns true if everything that can be done was applied
  92547. */
  92548. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92549. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92550. return true;
  92551. };
  92552. ;
  92553. return LensFlaresOptimization;
  92554. }(SceneOptimization));
  92555. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92556. /**
  92557. * Defines an optimization based on user defined callback.
  92558. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92559. */
  92560. var CustomOptimization = /** @class */ (function (_super) {
  92561. __extends(CustomOptimization, _super);
  92562. function CustomOptimization() {
  92563. return _super !== null && _super.apply(this, arguments) || this;
  92564. }
  92565. /**
  92566. * Gets a string describing the action executed by the current optimization
  92567. * @returns description string
  92568. */
  92569. CustomOptimization.prototype.getDescription = function () {
  92570. if (this.onGetDescription) {
  92571. return this.onGetDescription();
  92572. }
  92573. return "Running user defined callback";
  92574. };
  92575. /**
  92576. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92577. * @param scene defines the current scene where to apply this optimization
  92578. * @param optimizer defines the current optimizer
  92579. * @returns true if everything that can be done was applied
  92580. */
  92581. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92582. if (this.onApply) {
  92583. return this.onApply(scene, optimizer);
  92584. }
  92585. return true;
  92586. };
  92587. ;
  92588. return CustomOptimization;
  92589. }(SceneOptimization));
  92590. BABYLON.CustomOptimization = CustomOptimization;
  92591. /**
  92592. * Defines an optimization used to turn particles off
  92593. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92594. */
  92595. var ParticlesOptimization = /** @class */ (function (_super) {
  92596. __extends(ParticlesOptimization, _super);
  92597. function ParticlesOptimization() {
  92598. return _super !== null && _super.apply(this, arguments) || this;
  92599. }
  92600. /**
  92601. * Gets a string describing the action executed by the current optimization
  92602. * @return description string
  92603. */
  92604. ParticlesOptimization.prototype.getDescription = function () {
  92605. return "Turning particles on/off";
  92606. };
  92607. /**
  92608. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92609. * @param scene defines the current scene where to apply this optimization
  92610. * @param optimizer defines the current optimizer
  92611. * @returns true if everything that can be done was applied
  92612. */
  92613. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92614. scene.particlesEnabled = optimizer.isInImprovementMode;
  92615. return true;
  92616. };
  92617. ;
  92618. return ParticlesOptimization;
  92619. }(SceneOptimization));
  92620. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92621. /**
  92622. * Defines an optimization used to turn render targets off
  92623. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92624. */
  92625. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92626. __extends(RenderTargetsOptimization, _super);
  92627. function RenderTargetsOptimization() {
  92628. return _super !== null && _super.apply(this, arguments) || this;
  92629. }
  92630. /**
  92631. * Gets a string describing the action executed by the current optimization
  92632. * @return description string
  92633. */
  92634. RenderTargetsOptimization.prototype.getDescription = function () {
  92635. return "Turning render targets off";
  92636. };
  92637. /**
  92638. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92639. * @param scene defines the current scene where to apply this optimization
  92640. * @param optimizer defines the current optimizer
  92641. * @returns true if everything that can be done was applied
  92642. */
  92643. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92644. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92645. return true;
  92646. };
  92647. ;
  92648. return RenderTargetsOptimization;
  92649. }(SceneOptimization));
  92650. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92651. /**
  92652. * Defines an optimization used to merge meshes with compatible materials
  92653. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92654. */
  92655. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92656. __extends(MergeMeshesOptimization, _super);
  92657. function MergeMeshesOptimization() {
  92658. var _this = _super !== null && _super.apply(this, arguments) || this;
  92659. _this._canBeMerged = function (abstractMesh) {
  92660. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92661. return false;
  92662. }
  92663. var mesh = abstractMesh;
  92664. if (!mesh.isVisible || !mesh.isEnabled()) {
  92665. return false;
  92666. }
  92667. if (mesh.instances.length > 0) {
  92668. return false;
  92669. }
  92670. if (mesh.skeleton || mesh.hasLODLevels) {
  92671. return false;
  92672. }
  92673. if (mesh.parent) {
  92674. return false;
  92675. }
  92676. return true;
  92677. };
  92678. return _this;
  92679. }
  92680. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92681. /**
  92682. * Gets or sets a boolean which defines if optimization octree has to be updated
  92683. */
  92684. get: function () {
  92685. return MergeMeshesOptimization._UpdateSelectionTree;
  92686. },
  92687. /**
  92688. * Gets or sets a boolean which defines if optimization octree has to be updated
  92689. */
  92690. set: function (value) {
  92691. MergeMeshesOptimization._UpdateSelectionTree = value;
  92692. },
  92693. enumerable: true,
  92694. configurable: true
  92695. });
  92696. /**
  92697. * Gets a string describing the action executed by the current optimization
  92698. * @return description string
  92699. */
  92700. MergeMeshesOptimization.prototype.getDescription = function () {
  92701. return "Merging similar meshes together";
  92702. };
  92703. /**
  92704. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92705. * @param scene defines the current scene where to apply this optimization
  92706. * @param optimizer defines the current optimizer
  92707. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92708. * @returns true if everything that can be done was applied
  92709. */
  92710. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92711. var globalPool = scene.meshes.slice(0);
  92712. var globalLength = globalPool.length;
  92713. for (var index = 0; index < globalLength; index++) {
  92714. var currentPool = new Array();
  92715. var current = globalPool[index];
  92716. // Checks
  92717. if (!this._canBeMerged(current)) {
  92718. continue;
  92719. }
  92720. currentPool.push(current);
  92721. // Find compatible meshes
  92722. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92723. var otherMesh = globalPool[subIndex];
  92724. if (!this._canBeMerged(otherMesh)) {
  92725. continue;
  92726. }
  92727. if (otherMesh.material !== current.material) {
  92728. continue;
  92729. }
  92730. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92731. continue;
  92732. }
  92733. currentPool.push(otherMesh);
  92734. globalLength--;
  92735. globalPool.splice(subIndex, 1);
  92736. subIndex--;
  92737. }
  92738. if (currentPool.length < 2) {
  92739. continue;
  92740. }
  92741. // Merge meshes
  92742. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92743. }
  92744. if (updateSelectionTree != undefined) {
  92745. if (updateSelectionTree) {
  92746. scene.createOrUpdateSelectionOctree();
  92747. }
  92748. }
  92749. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92750. scene.createOrUpdateSelectionOctree();
  92751. }
  92752. return true;
  92753. };
  92754. ;
  92755. MergeMeshesOptimization._UpdateSelectionTree = false;
  92756. return MergeMeshesOptimization;
  92757. }(SceneOptimization));
  92758. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92759. /**
  92760. * Defines a list of options used by SceneOptimizer
  92761. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92762. */
  92763. var SceneOptimizerOptions = /** @class */ (function () {
  92764. /**
  92765. * Creates a new list of options used by SceneOptimizer
  92766. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92767. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92768. */
  92769. function SceneOptimizerOptions(
  92770. /**
  92771. * Defines the target frame rate to reach (60 by default)
  92772. */
  92773. targetFrameRate,
  92774. /**
  92775. * Defines the interval between two checkes (2000ms by default)
  92776. */
  92777. trackerDuration) {
  92778. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92779. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92780. this.targetFrameRate = targetFrameRate;
  92781. this.trackerDuration = trackerDuration;
  92782. /**
  92783. * Gets the list of optimizations to apply
  92784. */
  92785. this.optimizations = new Array();
  92786. }
  92787. /**
  92788. * Add a new optimization
  92789. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92790. * @returns the current SceneOptimizerOptions
  92791. */
  92792. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92793. this.optimizations.push(optimization);
  92794. return this;
  92795. };
  92796. /**
  92797. * Add a new custom optimization
  92798. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92799. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92800. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92801. * @returns the current SceneOptimizerOptions
  92802. */
  92803. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92804. if (priority === void 0) { priority = 0; }
  92805. var optimization = new CustomOptimization(priority);
  92806. optimization.onApply = onApply;
  92807. optimization.onGetDescription = onGetDescription;
  92808. this.optimizations.push(optimization);
  92809. return this;
  92810. };
  92811. /**
  92812. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92813. * @param targetFrameRate defines the target frame rate (60 by default)
  92814. * @returns a SceneOptimizerOptions object
  92815. */
  92816. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92817. var result = new SceneOptimizerOptions(targetFrameRate);
  92818. var priority = 0;
  92819. result.addOptimization(new MergeMeshesOptimization(priority));
  92820. result.addOptimization(new ShadowsOptimization(priority));
  92821. result.addOptimization(new LensFlaresOptimization(priority));
  92822. // Next priority
  92823. priority++;
  92824. result.addOptimization(new PostProcessesOptimization(priority));
  92825. result.addOptimization(new ParticlesOptimization(priority));
  92826. // Next priority
  92827. priority++;
  92828. result.addOptimization(new TextureOptimization(priority, 1024));
  92829. return result;
  92830. };
  92831. /**
  92832. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92833. * @param targetFrameRate defines the target frame rate (60 by default)
  92834. * @returns a SceneOptimizerOptions object
  92835. */
  92836. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92837. var result = new SceneOptimizerOptions(targetFrameRate);
  92838. var priority = 0;
  92839. result.addOptimization(new MergeMeshesOptimization(priority));
  92840. result.addOptimization(new ShadowsOptimization(priority));
  92841. result.addOptimization(new LensFlaresOptimization(priority));
  92842. // Next priority
  92843. priority++;
  92844. result.addOptimization(new PostProcessesOptimization(priority));
  92845. result.addOptimization(new ParticlesOptimization(priority));
  92846. // Next priority
  92847. priority++;
  92848. result.addOptimization(new TextureOptimization(priority, 512));
  92849. // Next priority
  92850. priority++;
  92851. result.addOptimization(new RenderTargetsOptimization(priority));
  92852. // Next priority
  92853. priority++;
  92854. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92855. return result;
  92856. };
  92857. /**
  92858. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92859. * @param targetFrameRate defines the target frame rate (60 by default)
  92860. * @returns a SceneOptimizerOptions object
  92861. */
  92862. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92863. var result = new SceneOptimizerOptions(targetFrameRate);
  92864. var priority = 0;
  92865. result.addOptimization(new MergeMeshesOptimization(priority));
  92866. result.addOptimization(new ShadowsOptimization(priority));
  92867. result.addOptimization(new LensFlaresOptimization(priority));
  92868. // Next priority
  92869. priority++;
  92870. result.addOptimization(new PostProcessesOptimization(priority));
  92871. result.addOptimization(new ParticlesOptimization(priority));
  92872. // Next priority
  92873. priority++;
  92874. result.addOptimization(new TextureOptimization(priority, 256));
  92875. // Next priority
  92876. priority++;
  92877. result.addOptimization(new RenderTargetsOptimization(priority));
  92878. // Next priority
  92879. priority++;
  92880. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92881. return result;
  92882. };
  92883. return SceneOptimizerOptions;
  92884. }());
  92885. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92886. /**
  92887. * Class used to run optimizations in order to reach a target frame rate
  92888. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92889. */
  92890. var SceneOptimizer = /** @class */ (function () {
  92891. /**
  92892. * Creates a new SceneOptimizer
  92893. * @param scene defines the scene to work on
  92894. * @param options defines the options to use with the SceneOptimizer
  92895. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92896. * @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)
  92897. */
  92898. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92899. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92900. if (improvementMode === void 0) { improvementMode = false; }
  92901. var _this = this;
  92902. this._isRunning = false;
  92903. this._currentPriorityLevel = 0;
  92904. this._targetFrameRate = 60;
  92905. this._trackerDuration = 2000;
  92906. this._currentFrameRate = 0;
  92907. this._improvementMode = false;
  92908. /**
  92909. * Defines an observable called when the optimizer reaches the target frame rate
  92910. */
  92911. this.onSuccessObservable = new BABYLON.Observable();
  92912. /**
  92913. * Defines an observable called when the optimizer enables an optimization
  92914. */
  92915. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92916. /**
  92917. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92918. */
  92919. this.onFailureObservable = new BABYLON.Observable();
  92920. if (!options) {
  92921. this._options = new SceneOptimizerOptions();
  92922. }
  92923. else {
  92924. this._options = options;
  92925. }
  92926. if (this._options.targetFrameRate) {
  92927. this._targetFrameRate = this._options.targetFrameRate;
  92928. }
  92929. if (this._options.trackerDuration) {
  92930. this._trackerDuration = this._options.trackerDuration;
  92931. }
  92932. if (autoGeneratePriorities) {
  92933. var priority = 0;
  92934. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92935. var optim = _a[_i];
  92936. optim.priority = priority++;
  92937. }
  92938. }
  92939. this._improvementMode = improvementMode;
  92940. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92941. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92942. _this._sceneDisposeObserver = null;
  92943. _this.dispose();
  92944. });
  92945. }
  92946. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92947. /**
  92948. * Gets a boolean indicating if the optimizer is in improvement mode
  92949. */
  92950. get: function () {
  92951. return this._improvementMode;
  92952. },
  92953. enumerable: true,
  92954. configurable: true
  92955. });
  92956. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92957. /**
  92958. * Gets the current priority level (0 at start)
  92959. */
  92960. get: function () {
  92961. return this._currentPriorityLevel;
  92962. },
  92963. enumerable: true,
  92964. configurable: true
  92965. });
  92966. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92967. /**
  92968. * Gets the current frame rate checked by the SceneOptimizer
  92969. */
  92970. get: function () {
  92971. return this._currentFrameRate;
  92972. },
  92973. enumerable: true,
  92974. configurable: true
  92975. });
  92976. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  92977. /**
  92978. * Gets or sets the current target frame rate (60 by default)
  92979. */
  92980. get: function () {
  92981. return this._targetFrameRate;
  92982. },
  92983. /**
  92984. * Gets or sets the current target frame rate (60 by default)
  92985. */
  92986. set: function (value) {
  92987. this._targetFrameRate = value;
  92988. },
  92989. enumerable: true,
  92990. configurable: true
  92991. });
  92992. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  92993. /**
  92994. * Gets or sets the current interval between two checks (every 2000ms by default)
  92995. */
  92996. get: function () {
  92997. return this._trackerDuration;
  92998. },
  92999. /**
  93000. * Gets or sets the current interval between two checks (every 2000ms by default)
  93001. */
  93002. set: function (value) {
  93003. this._trackerDuration = value;
  93004. },
  93005. enumerable: true,
  93006. configurable: true
  93007. });
  93008. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93009. /**
  93010. * Gets the list of active optimizations
  93011. */
  93012. get: function () {
  93013. return this._options.optimizations;
  93014. },
  93015. enumerable: true,
  93016. configurable: true
  93017. });
  93018. /**
  93019. * Stops the current optimizer
  93020. */
  93021. SceneOptimizer.prototype.stop = function () {
  93022. this._isRunning = false;
  93023. };
  93024. /**
  93025. * Reset the optimizer to initial step (current priority level = 0)
  93026. */
  93027. SceneOptimizer.prototype.reset = function () {
  93028. this._currentPriorityLevel = 0;
  93029. };
  93030. /**
  93031. * Start the optimizer. By default it will try to reach a specific framerate
  93032. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93033. */
  93034. SceneOptimizer.prototype.start = function () {
  93035. var _this = this;
  93036. if (this._isRunning) {
  93037. return;
  93038. }
  93039. this._isRunning = true;
  93040. // Let's wait for the scene to be ready before running our check
  93041. this._scene.executeWhenReady(function () {
  93042. setTimeout(function () {
  93043. _this._checkCurrentState();
  93044. }, _this._trackerDuration);
  93045. });
  93046. };
  93047. SceneOptimizer.prototype._checkCurrentState = function () {
  93048. var _this = this;
  93049. if (!this._isRunning) {
  93050. return;
  93051. }
  93052. var scene = this._scene;
  93053. var options = this._options;
  93054. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93055. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93056. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93057. this._isRunning = false;
  93058. this.onSuccessObservable.notifyObservers(this);
  93059. return;
  93060. }
  93061. // Apply current level of optimizations
  93062. var allDone = true;
  93063. var noOptimizationApplied = true;
  93064. for (var index = 0; index < options.optimizations.length; index++) {
  93065. var optimization = options.optimizations[index];
  93066. if (optimization.priority === this._currentPriorityLevel) {
  93067. noOptimizationApplied = false;
  93068. allDone = allDone && optimization.apply(scene, this);
  93069. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93070. }
  93071. }
  93072. // If no optimization was applied, this is a failure :(
  93073. if (noOptimizationApplied) {
  93074. this._isRunning = false;
  93075. this.onFailureObservable.notifyObservers(this);
  93076. return;
  93077. }
  93078. // If all optimizations were done, move to next level
  93079. if (allDone) {
  93080. this._currentPriorityLevel++;
  93081. }
  93082. // Let's the system running for a specific amount of time before checking FPS
  93083. scene.executeWhenReady(function () {
  93084. setTimeout(function () {
  93085. _this._checkCurrentState();
  93086. }, _this._trackerDuration);
  93087. });
  93088. };
  93089. /**
  93090. * Release all resources
  93091. */
  93092. SceneOptimizer.prototype.dispose = function () {
  93093. this.stop();
  93094. this.onSuccessObservable.clear();
  93095. this.onFailureObservable.clear();
  93096. this.onNewOptimizationAppliedObservable.clear();
  93097. if (this._sceneDisposeObserver) {
  93098. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93099. }
  93100. };
  93101. /**
  93102. * Helper function to create a SceneOptimizer with one single line of code
  93103. * @param scene defines the scene to work on
  93104. * @param options defines the options to use with the SceneOptimizer
  93105. * @param onSuccess defines a callback to call on success
  93106. * @param onFailure defines a callback to call on failure
  93107. * @returns the new SceneOptimizer object
  93108. */
  93109. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93110. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93111. if (onSuccess) {
  93112. optimizer.onSuccessObservable.add(function () {
  93113. onSuccess();
  93114. });
  93115. }
  93116. if (onFailure) {
  93117. optimizer.onFailureObservable.add(function () {
  93118. onFailure();
  93119. });
  93120. }
  93121. optimizer.start();
  93122. return optimizer;
  93123. };
  93124. return SceneOptimizer;
  93125. }());
  93126. BABYLON.SceneOptimizer = SceneOptimizer;
  93127. })(BABYLON || (BABYLON = {}));
  93128. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93129. var BABYLON;
  93130. (function (BABYLON) {
  93131. var OutlineRenderer = /** @class */ (function () {
  93132. function OutlineRenderer(scene) {
  93133. this.zOffset = 1;
  93134. this._scene = scene;
  93135. }
  93136. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93137. var _this = this;
  93138. if (useOverlay === void 0) { useOverlay = false; }
  93139. var scene = this._scene;
  93140. var engine = this._scene.getEngine();
  93141. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93142. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93143. return;
  93144. }
  93145. var mesh = subMesh.getRenderingMesh();
  93146. var material = subMesh.getMaterial();
  93147. if (!material || !scene.activeCamera) {
  93148. return;
  93149. }
  93150. engine.enableEffect(this._effect);
  93151. // Logarithmic depth
  93152. if (material.useLogarithmicDepth) {
  93153. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93154. }
  93155. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93156. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93157. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93158. // Bones
  93159. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93160. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93161. }
  93162. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93163. // Alpha test
  93164. if (material && material.needAlphaTesting()) {
  93165. var alphaTexture = material.getAlphaTestTexture();
  93166. if (alphaTexture) {
  93167. this._effect.setTexture("diffuseSampler", alphaTexture);
  93168. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93169. }
  93170. }
  93171. engine.setZOffset(-this.zOffset);
  93172. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93173. engine.setZOffset(0);
  93174. };
  93175. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93176. var defines = [];
  93177. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93178. var mesh = subMesh.getMesh();
  93179. var material = subMesh.getMaterial();
  93180. if (material) {
  93181. // Alpha test
  93182. if (material.needAlphaTesting()) {
  93183. defines.push("#define ALPHATEST");
  93184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93185. attribs.push(BABYLON.VertexBuffer.UVKind);
  93186. defines.push("#define UV1");
  93187. }
  93188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93189. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93190. defines.push("#define UV2");
  93191. }
  93192. }
  93193. //Logarithmic depth
  93194. if (material.useLogarithmicDepth) {
  93195. defines.push("#define LOGARITHMICDEPTH");
  93196. }
  93197. }
  93198. // Bones
  93199. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93202. if (mesh.numBoneInfluencers > 4) {
  93203. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93204. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93205. }
  93206. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93207. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93208. }
  93209. else {
  93210. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93211. }
  93212. // Instances
  93213. if (useInstances) {
  93214. defines.push("#define INSTANCES");
  93215. attribs.push("world0");
  93216. attribs.push("world1");
  93217. attribs.push("world2");
  93218. attribs.push("world3");
  93219. }
  93220. // Get correct effect
  93221. var join = defines.join("\n");
  93222. if (this._cachedDefines !== join) {
  93223. this._cachedDefines = join;
  93224. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93225. }
  93226. return this._effect.isReady();
  93227. };
  93228. return OutlineRenderer;
  93229. }());
  93230. BABYLON.OutlineRenderer = OutlineRenderer;
  93231. })(BABYLON || (BABYLON = {}));
  93232. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93233. var BABYLON;
  93234. (function (BABYLON) {
  93235. var FaceAdjacencies = /** @class */ (function () {
  93236. function FaceAdjacencies() {
  93237. this.edges = new Array();
  93238. this.edgesConnectedCount = 0;
  93239. }
  93240. return FaceAdjacencies;
  93241. }());
  93242. var EdgesRenderer = /** @class */ (function () {
  93243. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93244. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93245. if (epsilon === void 0) { epsilon = 0.95; }
  93246. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93247. this.edgesWidthScalerForOrthographic = 1000.0;
  93248. this.edgesWidthScalerForPerspective = 50.0;
  93249. this._linesPositions = new Array();
  93250. this._linesNormals = new Array();
  93251. this._linesIndices = new Array();
  93252. this._buffers = {};
  93253. this._checkVerticesInsteadOfIndices = false;
  93254. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93255. this.isEnabled = true;
  93256. this._source = source;
  93257. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93258. this._epsilon = epsilon;
  93259. this._prepareRessources();
  93260. this._generateEdgesLines();
  93261. }
  93262. EdgesRenderer.prototype._prepareRessources = function () {
  93263. if (this._lineShader) {
  93264. return;
  93265. }
  93266. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93267. attributes: ["position", "normal"],
  93268. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93269. });
  93270. this._lineShader.disableDepthWrite = true;
  93271. this._lineShader.backFaceCulling = false;
  93272. };
  93273. EdgesRenderer.prototype._rebuild = function () {
  93274. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93275. if (buffer) {
  93276. buffer._rebuild();
  93277. }
  93278. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93279. if (buffer) {
  93280. buffer._rebuild();
  93281. }
  93282. var scene = this._source.getScene();
  93283. var engine = scene.getEngine();
  93284. this._ib = engine.createIndexBuffer(this._linesIndices);
  93285. };
  93286. EdgesRenderer.prototype.dispose = function () {
  93287. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93288. if (buffer) {
  93289. buffer.dispose();
  93290. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93291. }
  93292. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93293. if (buffer) {
  93294. buffer.dispose();
  93295. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93296. }
  93297. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93298. this._lineShader.dispose();
  93299. };
  93300. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93301. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93302. return 0;
  93303. }
  93304. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93305. return 1;
  93306. }
  93307. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93308. return 2;
  93309. }
  93310. return -1;
  93311. };
  93312. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93313. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93314. return 0;
  93315. }
  93316. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93317. return 1;
  93318. }
  93319. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93320. return 2;
  93321. }
  93322. return -1;
  93323. };
  93324. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93325. var needToCreateLine;
  93326. if (edge === undefined) {
  93327. needToCreateLine = true;
  93328. }
  93329. else {
  93330. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93331. needToCreateLine = dotProduct < this._epsilon;
  93332. }
  93333. if (needToCreateLine) {
  93334. var offset = this._linesPositions.length / 3;
  93335. var normal = p0.subtract(p1);
  93336. normal.normalize();
  93337. // Positions
  93338. this._linesPositions.push(p0.x);
  93339. this._linesPositions.push(p0.y);
  93340. this._linesPositions.push(p0.z);
  93341. this._linesPositions.push(p0.x);
  93342. this._linesPositions.push(p0.y);
  93343. this._linesPositions.push(p0.z);
  93344. this._linesPositions.push(p1.x);
  93345. this._linesPositions.push(p1.y);
  93346. this._linesPositions.push(p1.z);
  93347. this._linesPositions.push(p1.x);
  93348. this._linesPositions.push(p1.y);
  93349. this._linesPositions.push(p1.z);
  93350. // Normals
  93351. this._linesNormals.push(p1.x);
  93352. this._linesNormals.push(p1.y);
  93353. this._linesNormals.push(p1.z);
  93354. this._linesNormals.push(-1);
  93355. this._linesNormals.push(p1.x);
  93356. this._linesNormals.push(p1.y);
  93357. this._linesNormals.push(p1.z);
  93358. this._linesNormals.push(1);
  93359. this._linesNormals.push(p0.x);
  93360. this._linesNormals.push(p0.y);
  93361. this._linesNormals.push(p0.z);
  93362. this._linesNormals.push(-1);
  93363. this._linesNormals.push(p0.x);
  93364. this._linesNormals.push(p0.y);
  93365. this._linesNormals.push(p0.z);
  93366. this._linesNormals.push(1);
  93367. // Indices
  93368. this._linesIndices.push(offset);
  93369. this._linesIndices.push(offset + 1);
  93370. this._linesIndices.push(offset + 2);
  93371. this._linesIndices.push(offset);
  93372. this._linesIndices.push(offset + 2);
  93373. this._linesIndices.push(offset + 3);
  93374. }
  93375. };
  93376. EdgesRenderer.prototype._generateEdgesLines = function () {
  93377. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93378. var indices = this._source.getIndices();
  93379. if (!indices || !positions) {
  93380. return;
  93381. }
  93382. // First let's find adjacencies
  93383. var adjacencies = new Array();
  93384. var faceNormals = new Array();
  93385. var index;
  93386. var faceAdjacencies;
  93387. // Prepare faces
  93388. for (index = 0; index < indices.length; index += 3) {
  93389. faceAdjacencies = new FaceAdjacencies();
  93390. var p0Index = indices[index];
  93391. var p1Index = indices[index + 1];
  93392. var p2Index = indices[index + 2];
  93393. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93394. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93395. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93396. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93397. faceNormal.normalize();
  93398. faceNormals.push(faceNormal);
  93399. adjacencies.push(faceAdjacencies);
  93400. }
  93401. // Scan
  93402. for (index = 0; index < adjacencies.length; index++) {
  93403. faceAdjacencies = adjacencies[index];
  93404. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93405. var otherFaceAdjacencies = adjacencies[otherIndex];
  93406. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93407. break;
  93408. }
  93409. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93410. continue;
  93411. }
  93412. var otherP0 = indices[otherIndex * 3];
  93413. var otherP1 = indices[otherIndex * 3 + 1];
  93414. var otherP2 = indices[otherIndex * 3 + 2];
  93415. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93416. var otherEdgeIndex = 0;
  93417. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93418. continue;
  93419. }
  93420. switch (edgeIndex) {
  93421. case 0:
  93422. if (this._checkVerticesInsteadOfIndices) {
  93423. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93424. }
  93425. else {
  93426. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93427. }
  93428. break;
  93429. case 1:
  93430. if (this._checkVerticesInsteadOfIndices) {
  93431. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93432. }
  93433. else {
  93434. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93435. }
  93436. break;
  93437. case 2:
  93438. if (this._checkVerticesInsteadOfIndices) {
  93439. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93440. }
  93441. else {
  93442. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93443. }
  93444. break;
  93445. }
  93446. if (otherEdgeIndex === -1) {
  93447. continue;
  93448. }
  93449. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93450. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93451. faceAdjacencies.edgesConnectedCount++;
  93452. otherFaceAdjacencies.edgesConnectedCount++;
  93453. if (faceAdjacencies.edgesConnectedCount === 3) {
  93454. break;
  93455. }
  93456. }
  93457. }
  93458. }
  93459. // Create lines
  93460. for (index = 0; index < adjacencies.length; index++) {
  93461. // 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
  93462. var current = adjacencies[index];
  93463. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93464. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93465. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93466. }
  93467. // Merge into a single mesh
  93468. var engine = this._source.getScene().getEngine();
  93469. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93470. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93471. this._ib = engine.createIndexBuffer(this._linesIndices);
  93472. this._indicesCount = this._linesIndices.length;
  93473. };
  93474. EdgesRenderer.prototype.render = function () {
  93475. var scene = this._source.getScene();
  93476. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93477. return;
  93478. }
  93479. var engine = scene.getEngine();
  93480. this._lineShader._preBind();
  93481. // VBOs
  93482. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93483. scene.resetCachedMaterial();
  93484. this._lineShader.setColor4("color", this._source.edgesColor);
  93485. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93486. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93487. }
  93488. else {
  93489. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93490. }
  93491. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93492. this._lineShader.bind(this._source.getWorldMatrix());
  93493. // Draw order
  93494. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93495. this._lineShader.unbind();
  93496. engine.setDepthWrite(true);
  93497. };
  93498. return EdgesRenderer;
  93499. }());
  93500. BABYLON.EdgesRenderer = EdgesRenderer;
  93501. })(BABYLON || (BABYLON = {}));
  93502. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93503. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93504. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93505. s = arguments[i];
  93506. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93507. t[p] = s[p];
  93508. }
  93509. return t;
  93510. };
  93511. var BABYLON;
  93512. (function (BABYLON) {
  93513. /**
  93514. * The effect layer Helps adding post process effect blended with the main pass.
  93515. *
  93516. * This can be for instance use to generate glow or higlight effects on the scene.
  93517. *
  93518. * The effect layer class can not be used directly and is intented to inherited from to be
  93519. * customized per effects.
  93520. */
  93521. var EffectLayer = /** @class */ (function () {
  93522. /**
  93523. * Instantiates a new effect Layer and references it in the scene.
  93524. * @param name The name of the layer
  93525. * @param scene The scene to use the layer in
  93526. */
  93527. function EffectLayer(
  93528. /** The Friendly of the effect in the scene */
  93529. name, scene) {
  93530. this._vertexBuffers = {};
  93531. this._maxSize = 0;
  93532. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93533. this._shouldRender = true;
  93534. this._postProcesses = [];
  93535. this._textures = [];
  93536. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93537. /**
  93538. * The clear color of the texture used to generate the glow map.
  93539. */
  93540. this.neutralColor = new BABYLON.Color4();
  93541. /**
  93542. * Specifies wether the highlight layer is enabled or not.
  93543. */
  93544. this.isEnabled = true;
  93545. /**
  93546. * An event triggered when the effect layer has been disposed.
  93547. */
  93548. this.onDisposeObservable = new BABYLON.Observable();
  93549. /**
  93550. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93551. */
  93552. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93553. /**
  93554. * An event triggered when the generated texture is being merged in the scene.
  93555. */
  93556. this.onBeforeComposeObservable = new BABYLON.Observable();
  93557. /**
  93558. * An event triggered when the generated texture has been merged in the scene.
  93559. */
  93560. this.onAfterComposeObservable = new BABYLON.Observable();
  93561. /**
  93562. * An event triggered when the efffect layer changes its size.
  93563. */
  93564. this.onSizeChangedObservable = new BABYLON.Observable();
  93565. this.name = name;
  93566. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93567. this._engine = scene.getEngine();
  93568. this._maxSize = this._engine.getCaps().maxTextureSize;
  93569. this._scene.effectLayers.push(this);
  93570. // Generate Buffers
  93571. this._generateIndexBuffer();
  93572. this._genrateVertexBuffer();
  93573. }
  93574. Object.defineProperty(EffectLayer.prototype, "camera", {
  93575. /**
  93576. * Gets the camera attached to the layer.
  93577. */
  93578. get: function () {
  93579. return this._effectLayerOptions.camera;
  93580. },
  93581. enumerable: true,
  93582. configurable: true
  93583. });
  93584. /**
  93585. * Initializes the effect layer with the required options.
  93586. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93587. */
  93588. EffectLayer.prototype._init = function (options) {
  93589. // Adapt options
  93590. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93591. this._setMainTextureSize();
  93592. this._createMainTexture();
  93593. this._createTextureAndPostProcesses();
  93594. this._mergeEffect = this._createMergeEffect();
  93595. };
  93596. /**
  93597. * Generates the index buffer of the full screen quad blending to the main canvas.
  93598. */
  93599. EffectLayer.prototype._generateIndexBuffer = function () {
  93600. // Indices
  93601. var indices = [];
  93602. indices.push(0);
  93603. indices.push(1);
  93604. indices.push(2);
  93605. indices.push(0);
  93606. indices.push(2);
  93607. indices.push(3);
  93608. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93609. };
  93610. /**
  93611. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93612. */
  93613. EffectLayer.prototype._genrateVertexBuffer = function () {
  93614. // VBO
  93615. var vertices = [];
  93616. vertices.push(1, 1);
  93617. vertices.push(-1, 1);
  93618. vertices.push(-1, -1);
  93619. vertices.push(1, -1);
  93620. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93621. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93622. };
  93623. /**
  93624. * Sets the main texture desired size which is the closest power of two
  93625. * of the engine canvas size.
  93626. */
  93627. EffectLayer.prototype._setMainTextureSize = function () {
  93628. if (this._effectLayerOptions.mainTextureFixedSize) {
  93629. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93630. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93631. }
  93632. else {
  93633. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93634. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93635. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93636. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93637. }
  93638. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93639. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93640. };
  93641. /**
  93642. * Creates the main texture for the effect layer.
  93643. */
  93644. EffectLayer.prototype._createMainTexture = function () {
  93645. var _this = this;
  93646. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93647. width: this._mainTextureDesiredSize.width,
  93648. height: this._mainTextureDesiredSize.height
  93649. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93650. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93651. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93652. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93653. this._mainTexture.anisotropicFilteringLevel = 1;
  93654. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93655. this._mainTexture.renderParticles = false;
  93656. this._mainTexture.renderList = null;
  93657. this._mainTexture.ignoreCameraViewport = true;
  93658. // Custom render function
  93659. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93660. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93661. var index;
  93662. var engine = _this._scene.getEngine();
  93663. if (depthOnlySubMeshes.length) {
  93664. engine.setColorWrite(false);
  93665. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93666. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93667. }
  93668. engine.setColorWrite(true);
  93669. }
  93670. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93671. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93672. }
  93673. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93674. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93675. }
  93676. for (index = 0; index < transparentSubMeshes.length; index++) {
  93677. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93678. }
  93679. };
  93680. this._mainTexture.onClearObservable.add(function (engine) {
  93681. engine.clear(_this.neutralColor, true, true, true);
  93682. });
  93683. };
  93684. /**
  93685. * Checks for the readiness of the element composing the layer.
  93686. * @param subMesh the mesh to check for
  93687. * @param useInstances specify wether or not to use instances to render the mesh
  93688. * @param emissiveTexture the associated emissive texture used to generate the glow
  93689. * @return true if ready otherwise, false
  93690. */
  93691. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93692. var material = subMesh.getMaterial();
  93693. if (!material) {
  93694. return false;
  93695. }
  93696. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93697. return false;
  93698. }
  93699. var defines = [];
  93700. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93701. var mesh = subMesh.getMesh();
  93702. var uv1 = false;
  93703. var uv2 = false;
  93704. // Alpha test
  93705. if (material && material.needAlphaTesting()) {
  93706. var alphaTexture = material.getAlphaTestTexture();
  93707. if (alphaTexture) {
  93708. defines.push("#define ALPHATEST");
  93709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93710. alphaTexture.coordinatesIndex === 1) {
  93711. defines.push("#define DIFFUSEUV2");
  93712. uv2 = true;
  93713. }
  93714. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93715. defines.push("#define DIFFUSEUV1");
  93716. uv1 = true;
  93717. }
  93718. }
  93719. }
  93720. // Emissive
  93721. if (emissiveTexture) {
  93722. defines.push("#define EMISSIVE");
  93723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93724. emissiveTexture.coordinatesIndex === 1) {
  93725. defines.push("#define EMISSIVEUV2");
  93726. uv2 = true;
  93727. }
  93728. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93729. defines.push("#define EMISSIVEUV1");
  93730. uv1 = true;
  93731. }
  93732. }
  93733. if (uv1) {
  93734. attribs.push(BABYLON.VertexBuffer.UVKind);
  93735. defines.push("#define UV1");
  93736. }
  93737. if (uv2) {
  93738. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93739. defines.push("#define UV2");
  93740. }
  93741. // Bones
  93742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93745. if (mesh.numBoneInfluencers > 4) {
  93746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93748. }
  93749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93750. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93751. }
  93752. else {
  93753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93754. }
  93755. // Morph targets
  93756. var manager = mesh.morphTargetManager;
  93757. var morphInfluencers = 0;
  93758. if (manager) {
  93759. if (manager.numInfluencers > 0) {
  93760. defines.push("#define MORPHTARGETS");
  93761. morphInfluencers = manager.numInfluencers;
  93762. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93763. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93764. }
  93765. }
  93766. // Instances
  93767. if (useInstances) {
  93768. defines.push("#define INSTANCES");
  93769. attribs.push("world0");
  93770. attribs.push("world1");
  93771. attribs.push("world2");
  93772. attribs.push("world3");
  93773. }
  93774. // Get correct effect
  93775. var join = defines.join("\n");
  93776. if (this._cachedDefines !== join) {
  93777. this._cachedDefines = join;
  93778. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93779. }
  93780. return this._effectLayerMapGenerationEffect.isReady();
  93781. };
  93782. /**
  93783. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93784. */
  93785. EffectLayer.prototype.render = function () {
  93786. var currentEffect = this._mergeEffect;
  93787. // Check
  93788. if (!currentEffect.isReady())
  93789. return;
  93790. for (var i = 0; i < this._postProcesses.length; i++) {
  93791. if (!this._postProcesses[i].isReady()) {
  93792. return;
  93793. }
  93794. }
  93795. var engine = this._scene.getEngine();
  93796. this.onBeforeComposeObservable.notifyObservers(this);
  93797. // Render
  93798. engine.enableEffect(currentEffect);
  93799. engine.setState(false);
  93800. // VBOs
  93801. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93802. // Cache
  93803. var previousAlphaMode = engine.getAlphaMode();
  93804. // Go Blend.
  93805. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93806. // Blends the map on the main canvas.
  93807. this._internalRender(currentEffect);
  93808. // Restore Alpha
  93809. engine.setAlphaMode(previousAlphaMode);
  93810. this.onAfterComposeObservable.notifyObservers(this);
  93811. // Handle size changes.
  93812. var size = this._mainTexture.getSize();
  93813. this._setMainTextureSize();
  93814. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93815. // Recreate RTT and post processes on size change.
  93816. this.onSizeChangedObservable.notifyObservers(this);
  93817. this._disposeTextureAndPostProcesses();
  93818. this._createMainTexture();
  93819. this._createTextureAndPostProcesses();
  93820. }
  93821. };
  93822. /**
  93823. * Determine if a given mesh will be used in the current effect.
  93824. * @param mesh mesh to test
  93825. * @returns true if the mesh will be used
  93826. */
  93827. EffectLayer.prototype.hasMesh = function (mesh) {
  93828. return true;
  93829. };
  93830. /**
  93831. * Returns true if the layer contains information to display, otherwise false.
  93832. * @returns true if the glow layer should be rendered
  93833. */
  93834. EffectLayer.prototype.shouldRender = function () {
  93835. return this.isEnabled && this._shouldRender;
  93836. };
  93837. /**
  93838. * Returns true if the mesh should render, otherwise false.
  93839. * @param mesh The mesh to render
  93840. * @returns true if it should render otherwise false
  93841. */
  93842. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93843. return true;
  93844. };
  93845. /**
  93846. * Returns true if the mesh should render, otherwise false.
  93847. * @param mesh The mesh to render
  93848. * @returns true if it should render otherwise false
  93849. */
  93850. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93851. return true;
  93852. };
  93853. /**
  93854. * Renders the submesh passed in parameter to the generation map.
  93855. */
  93856. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93857. var _this = this;
  93858. if (!this.shouldRender()) {
  93859. return;
  93860. }
  93861. var material = subMesh.getMaterial();
  93862. var mesh = subMesh.getRenderingMesh();
  93863. var scene = this._scene;
  93864. var engine = scene.getEngine();
  93865. if (!material) {
  93866. return;
  93867. }
  93868. // Do not block in blend mode.
  93869. if (material.needAlphaBlendingForMesh(mesh)) {
  93870. return;
  93871. }
  93872. // Culling
  93873. engine.setState(material.backFaceCulling);
  93874. // Managing instances
  93875. var batch = mesh._getInstancesRenderList(subMesh._id);
  93876. if (batch.mustReturn) {
  93877. return;
  93878. }
  93879. // Early Exit per mesh
  93880. if (!this._shouldRenderMesh(mesh)) {
  93881. return;
  93882. }
  93883. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93884. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93885. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93886. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93887. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93888. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93889. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93890. // Alpha test
  93891. if (material && material.needAlphaTesting()) {
  93892. var alphaTexture = material.getAlphaTestTexture();
  93893. if (alphaTexture) {
  93894. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93895. var textureMatrix = alphaTexture.getTextureMatrix();
  93896. if (textureMatrix) {
  93897. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93898. }
  93899. }
  93900. }
  93901. // Glow emissive only
  93902. if (this._emissiveTextureAndColor.texture) {
  93903. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93904. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93905. }
  93906. // Bones
  93907. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93908. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93909. }
  93910. // Morph targets
  93911. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93912. // Draw
  93913. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93914. }
  93915. else {
  93916. // Need to reset refresh rate of the shadowMap
  93917. this._mainTexture.resetRefreshCounter();
  93918. }
  93919. };
  93920. /**
  93921. * Rebuild the required buffers.
  93922. * @hidden Internal use only.
  93923. */
  93924. EffectLayer.prototype._rebuild = function () {
  93925. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93926. if (vb) {
  93927. vb._rebuild();
  93928. }
  93929. this._generateIndexBuffer();
  93930. };
  93931. /**
  93932. * Dispose only the render target textures and post process.
  93933. */
  93934. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93935. this._mainTexture.dispose();
  93936. for (var i = 0; i < this._postProcesses.length; i++) {
  93937. if (this._postProcesses[i]) {
  93938. this._postProcesses[i].dispose();
  93939. }
  93940. }
  93941. this._postProcesses = [];
  93942. for (var i = 0; i < this._textures.length; i++) {
  93943. if (this._textures[i]) {
  93944. this._textures[i].dispose();
  93945. }
  93946. }
  93947. this._textures = [];
  93948. };
  93949. /**
  93950. * Dispose the highlight layer and free resources.
  93951. */
  93952. EffectLayer.prototype.dispose = function () {
  93953. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93954. if (vertexBuffer) {
  93955. vertexBuffer.dispose();
  93956. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93957. }
  93958. if (this._indexBuffer) {
  93959. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93960. this._indexBuffer = null;
  93961. }
  93962. // Clean textures and post processes
  93963. this._disposeTextureAndPostProcesses();
  93964. // Remove from scene
  93965. var index = this._scene.effectLayers.indexOf(this, 0);
  93966. if (index > -1) {
  93967. this._scene.effectLayers.splice(index, 1);
  93968. }
  93969. // Callback
  93970. this.onDisposeObservable.notifyObservers(this);
  93971. this.onDisposeObservable.clear();
  93972. this.onBeforeRenderMainTextureObservable.clear();
  93973. this.onBeforeComposeObservable.clear();
  93974. this.onAfterComposeObservable.clear();
  93975. this.onSizeChangedObservable.clear();
  93976. };
  93977. /**
  93978. * Gets the class name of the effect layer
  93979. * @returns the string with the class name of the effect layer
  93980. */
  93981. EffectLayer.prototype.getClassName = function () {
  93982. return "EffectLayer";
  93983. };
  93984. /**
  93985. * Creates an effect layer from parsed effect layer data
  93986. * @param parsedEffectLayer defines effect layer data
  93987. * @param scene defines the current scene
  93988. * @param rootUrl defines the root URL containing the effect layer information
  93989. * @returns a parsed effect Layer
  93990. */
  93991. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  93992. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  93993. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  93994. };
  93995. __decorate([
  93996. BABYLON.serialize()
  93997. ], EffectLayer.prototype, "name", void 0);
  93998. __decorate([
  93999. BABYLON.serializeAsColor4()
  94000. ], EffectLayer.prototype, "neutralColor", void 0);
  94001. __decorate([
  94002. BABYLON.serialize()
  94003. ], EffectLayer.prototype, "isEnabled", void 0);
  94004. __decorate([
  94005. BABYLON.serializeAsCameraReference()
  94006. ], EffectLayer.prototype, "camera", null);
  94007. return EffectLayer;
  94008. }());
  94009. BABYLON.EffectLayer = EffectLayer;
  94010. })(BABYLON || (BABYLON = {}));
  94011. //# sourceMappingURL=babylon.effectLayer.js.map
  94012. var BABYLON;
  94013. (function (BABYLON) {
  94014. /**
  94015. * Special Glow Blur post process only blurring the alpha channel
  94016. * It enforces keeping the most luminous color in the color channel.
  94017. */
  94018. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94019. __extends(GlowBlurPostProcess, _super);
  94020. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94022. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94023. _this.direction = direction;
  94024. _this.kernel = kernel;
  94025. _this.onApplyObservable.add(function (effect) {
  94026. effect.setFloat2("screenSize", _this.width, _this.height);
  94027. effect.setVector2("direction", _this.direction);
  94028. effect.setFloat("blurWidth", _this.kernel);
  94029. });
  94030. return _this;
  94031. }
  94032. return GlowBlurPostProcess;
  94033. }(BABYLON.PostProcess));
  94034. /**
  94035. * The highlight layer Helps adding a glow effect around a mesh.
  94036. *
  94037. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94038. * glowy meshes to your scene.
  94039. *
  94040. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94041. */
  94042. var HighlightLayer = /** @class */ (function (_super) {
  94043. __extends(HighlightLayer, _super);
  94044. /**
  94045. * Instantiates a new highlight Layer and references it to the scene..
  94046. * @param name The name of the layer
  94047. * @param scene The scene to use the layer in
  94048. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94049. */
  94050. function HighlightLayer(name, scene, options) {
  94051. var _this = _super.call(this, name, scene) || this;
  94052. _this.name = name;
  94053. /**
  94054. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94055. */
  94056. _this.innerGlow = true;
  94057. /**
  94058. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94059. */
  94060. _this.outerGlow = true;
  94061. /**
  94062. * An event triggered when the highlight layer is being blurred.
  94063. */
  94064. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94065. /**
  94066. * An event triggered when the highlight layer has been blurred.
  94067. */
  94068. _this.onAfterBlurObservable = new BABYLON.Observable();
  94069. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94070. _this._meshes = {};
  94071. _this._excludedMeshes = {};
  94072. _this.neutralColor = HighlightLayer.NeutralColor;
  94073. // Warn on stencil
  94074. if (!_this._engine.isStencilEnable) {
  94075. 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 }");
  94076. }
  94077. // Adapt options
  94078. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94079. // Initialize the layer
  94080. _this._init({
  94081. alphaBlendingMode: _this._options.alphaBlendingMode,
  94082. camera: _this._options.camera,
  94083. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94084. mainTextureRatio: _this._options.mainTextureRatio
  94085. });
  94086. // Do not render as long as no meshes have been added
  94087. _this._shouldRender = false;
  94088. return _this;
  94089. }
  94090. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94091. /**
  94092. * Gets the horizontal size of the blur.
  94093. */
  94094. get: function () {
  94095. return this._horizontalBlurPostprocess.kernel;
  94096. },
  94097. /**
  94098. * Specifies the horizontal size of the blur.
  94099. */
  94100. set: function (value) {
  94101. this._horizontalBlurPostprocess.kernel = value;
  94102. },
  94103. enumerable: true,
  94104. configurable: true
  94105. });
  94106. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94107. /**
  94108. * Gets the vertical size of the blur.
  94109. */
  94110. get: function () {
  94111. return this._verticalBlurPostprocess.kernel;
  94112. },
  94113. /**
  94114. * Specifies the vertical size of the blur.
  94115. */
  94116. set: function (value) {
  94117. this._verticalBlurPostprocess.kernel = value;
  94118. },
  94119. enumerable: true,
  94120. configurable: true
  94121. });
  94122. /**
  94123. * Get the effect name of the layer.
  94124. * @return The effect name
  94125. */
  94126. HighlightLayer.prototype.getEffectName = function () {
  94127. return HighlightLayer.EffectName;
  94128. };
  94129. /**
  94130. * Create the merge effect. This is the shader use to blit the information back
  94131. * to the main canvas at the end of the scene rendering.
  94132. */
  94133. HighlightLayer.prototype._createMergeEffect = function () {
  94134. // Effect
  94135. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94136. };
  94137. /**
  94138. * Creates the render target textures and post processes used in the highlight layer.
  94139. */
  94140. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94141. var _this = this;
  94142. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94143. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94144. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94145. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94146. var textureType = 0;
  94147. if (this._engine.getCaps().textureHalfFloatRender) {
  94148. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94149. }
  94150. else {
  94151. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94152. }
  94153. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94154. width: blurTextureWidth,
  94155. height: blurTextureHeight
  94156. }, this._scene, false, true, textureType);
  94157. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94158. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94159. this._blurTexture.anisotropicFilteringLevel = 16;
  94160. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94161. this._blurTexture.renderParticles = false;
  94162. this._blurTexture.ignoreCameraViewport = true;
  94163. this._textures = [this._blurTexture];
  94164. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94165. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94166. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94167. effect.setTexture("textureSampler", _this._mainTexture);
  94168. });
  94169. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94170. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94171. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94172. });
  94173. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94174. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94175. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94176. });
  94177. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94178. }
  94179. else {
  94180. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94181. width: blurTextureWidth,
  94182. height: blurTextureHeight
  94183. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94184. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94185. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94186. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94187. effect.setTexture("textureSampler", _this._mainTexture);
  94188. });
  94189. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94190. width: blurTextureWidth,
  94191. height: blurTextureHeight
  94192. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94193. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94194. }
  94195. this._mainTexture.onAfterUnbindObservable.add(function () {
  94196. _this.onBeforeBlurObservable.notifyObservers(_this);
  94197. var internalTexture = _this._blurTexture.getInternalTexture();
  94198. if (internalTexture) {
  94199. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94200. }
  94201. _this.onAfterBlurObservable.notifyObservers(_this);
  94202. });
  94203. // Prevent autoClear.
  94204. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94205. };
  94206. /**
  94207. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94208. */
  94209. HighlightLayer.prototype.needStencil = function () {
  94210. return true;
  94211. };
  94212. /**
  94213. * Checks for the readiness of the element composing the layer.
  94214. * @param subMesh the mesh to check for
  94215. * @param useInstances specify wether or not to use instances to render the mesh
  94216. * @param emissiveTexture the associated emissive texture used to generate the glow
  94217. * @return true if ready otherwise, false
  94218. */
  94219. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94220. var material = subMesh.getMaterial();
  94221. var mesh = subMesh.getRenderingMesh();
  94222. if (!material || !mesh || !this._meshes) {
  94223. return false;
  94224. }
  94225. var emissiveTexture = null;
  94226. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94227. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94228. emissiveTexture = material.emissiveTexture;
  94229. }
  94230. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94231. };
  94232. /**
  94233. * Implementation specific of rendering the generating effect on the main canvas.
  94234. * @param effect The effect used to render through
  94235. */
  94236. HighlightLayer.prototype._internalRender = function (effect) {
  94237. // Texture
  94238. effect.setTexture("textureSampler", this._blurTexture);
  94239. // Cache
  94240. var engine = this._engine;
  94241. var previousStencilBuffer = engine.getStencilBuffer();
  94242. var previousStencilFunction = engine.getStencilFunction();
  94243. var previousStencilMask = engine.getStencilMask();
  94244. var previousStencilOperationPass = engine.getStencilOperationPass();
  94245. var previousStencilOperationFail = engine.getStencilOperationFail();
  94246. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94247. var previousStencilReference = engine.getStencilFunctionReference();
  94248. // Stencil operations
  94249. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94250. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94251. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94252. // Draw order
  94253. engine.setStencilMask(0x00);
  94254. engine.setStencilBuffer(true);
  94255. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94256. // 2 passes inner outer
  94257. if (this.outerGlow) {
  94258. effect.setFloat("offset", 0);
  94259. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94260. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94261. }
  94262. if (this.innerGlow) {
  94263. effect.setFloat("offset", 1);
  94264. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94265. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94266. }
  94267. // Restore Cache
  94268. engine.setStencilFunction(previousStencilFunction);
  94269. engine.setStencilMask(previousStencilMask);
  94270. engine.setStencilBuffer(previousStencilBuffer);
  94271. engine.setStencilOperationPass(previousStencilOperationPass);
  94272. engine.setStencilOperationFail(previousStencilOperationFail);
  94273. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94274. engine.setStencilFunctionReference(previousStencilReference);
  94275. };
  94276. /**
  94277. * Returns true if the layer contains information to display, otherwise false.
  94278. */
  94279. HighlightLayer.prototype.shouldRender = function () {
  94280. if (_super.prototype.shouldRender.call(this)) {
  94281. return this._meshes ? true : false;
  94282. }
  94283. return false;
  94284. };
  94285. /**
  94286. * Returns true if the mesh should render, otherwise false.
  94287. * @param mesh The mesh to render
  94288. * @returns true if it should render otherwise false
  94289. */
  94290. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94291. // Excluded Mesh
  94292. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94293. return false;
  94294. }
  94295. ;
  94296. return true;
  94297. };
  94298. /**
  94299. * Sets the required values for both the emissive texture and and the main color.
  94300. */
  94301. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94302. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94303. if (highlightLayerMesh) {
  94304. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94305. }
  94306. else {
  94307. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94308. }
  94309. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94310. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94311. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94312. }
  94313. else {
  94314. this._emissiveTextureAndColor.texture = null;
  94315. }
  94316. };
  94317. /**
  94318. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94319. * @param mesh The mesh to exclude from the highlight layer
  94320. */
  94321. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94322. if (!this._excludedMeshes) {
  94323. return;
  94324. }
  94325. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94326. if (!meshExcluded) {
  94327. this._excludedMeshes[mesh.uniqueId] = {
  94328. mesh: mesh,
  94329. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94330. mesh.getEngine().setStencilBuffer(false);
  94331. }),
  94332. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94333. mesh.getEngine().setStencilBuffer(true);
  94334. }),
  94335. };
  94336. }
  94337. };
  94338. /**
  94339. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94340. * @param mesh The mesh to highlight
  94341. */
  94342. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94343. if (!this._excludedMeshes) {
  94344. return;
  94345. }
  94346. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94347. if (meshExcluded) {
  94348. if (meshExcluded.beforeRender) {
  94349. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94350. }
  94351. if (meshExcluded.afterRender) {
  94352. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94353. }
  94354. }
  94355. this._excludedMeshes[mesh.uniqueId] = null;
  94356. };
  94357. /**
  94358. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94359. * @param mesh mesh to test
  94360. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94361. */
  94362. HighlightLayer.prototype.hasMesh = function (mesh) {
  94363. if (!this._meshes) {
  94364. return false;
  94365. }
  94366. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94367. };
  94368. /**
  94369. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94370. * @param mesh The mesh to highlight
  94371. * @param color The color of the highlight
  94372. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94373. */
  94374. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94375. var _this = this;
  94376. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94377. if (!this._meshes) {
  94378. return;
  94379. }
  94380. var meshHighlight = this._meshes[mesh.uniqueId];
  94381. if (meshHighlight) {
  94382. meshHighlight.color = color;
  94383. }
  94384. else {
  94385. this._meshes[mesh.uniqueId] = {
  94386. mesh: mesh,
  94387. color: color,
  94388. // Lambda required for capture due to Observable this context
  94389. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94390. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94391. _this._defaultStencilReference(mesh);
  94392. }
  94393. else {
  94394. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94395. }
  94396. }),
  94397. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94398. glowEmissiveOnly: glowEmissiveOnly
  94399. };
  94400. }
  94401. this._shouldRender = true;
  94402. };
  94403. /**
  94404. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94405. * @param mesh The mesh to highlight
  94406. */
  94407. HighlightLayer.prototype.removeMesh = function (mesh) {
  94408. if (!this._meshes) {
  94409. return;
  94410. }
  94411. var meshHighlight = this._meshes[mesh.uniqueId];
  94412. if (meshHighlight) {
  94413. if (meshHighlight.observerHighlight) {
  94414. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94415. }
  94416. if (meshHighlight.observerDefault) {
  94417. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94418. }
  94419. delete this._meshes[mesh.uniqueId];
  94420. }
  94421. this._shouldRender = false;
  94422. for (var meshHighlightToCheck in this._meshes) {
  94423. if (this._meshes[meshHighlightToCheck]) {
  94424. this._shouldRender = true;
  94425. break;
  94426. }
  94427. }
  94428. };
  94429. /**
  94430. * Force the stencil to the normal expected value for none glowing parts
  94431. */
  94432. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94433. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94434. };
  94435. /**
  94436. * Free any resources and references associated to a mesh.
  94437. * Internal use
  94438. * @param mesh The mesh to free.
  94439. */
  94440. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94441. this.removeMesh(mesh);
  94442. this.removeExcludedMesh(mesh);
  94443. };
  94444. /**
  94445. * Dispose the highlight layer and free resources.
  94446. */
  94447. HighlightLayer.prototype.dispose = function () {
  94448. if (this._meshes) {
  94449. // Clean mesh references
  94450. for (var id in this._meshes) {
  94451. var meshHighlight = this._meshes[id];
  94452. if (meshHighlight && meshHighlight.mesh) {
  94453. if (meshHighlight.observerHighlight) {
  94454. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94455. }
  94456. if (meshHighlight.observerDefault) {
  94457. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94458. }
  94459. }
  94460. }
  94461. this._meshes = null;
  94462. }
  94463. if (this._excludedMeshes) {
  94464. for (var id in this._excludedMeshes) {
  94465. var meshHighlight = this._excludedMeshes[id];
  94466. if (meshHighlight) {
  94467. if (meshHighlight.beforeRender) {
  94468. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94469. }
  94470. if (meshHighlight.afterRender) {
  94471. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94472. }
  94473. }
  94474. }
  94475. this._excludedMeshes = null;
  94476. }
  94477. _super.prototype.dispose.call(this);
  94478. };
  94479. /**
  94480. * Gets the class name of the effect layer
  94481. * @returns the string with the class name of the effect layer
  94482. */
  94483. HighlightLayer.prototype.getClassName = function () {
  94484. return "HighlightLayer";
  94485. };
  94486. /**
  94487. * Serializes this Highlight layer
  94488. * @returns a serialized Highlight layer object
  94489. */
  94490. HighlightLayer.prototype.serialize = function () {
  94491. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94492. serializationObject.customType = "BABYLON.HighlightLayer";
  94493. // Highlighted meshes
  94494. serializationObject.meshes = [];
  94495. if (this._meshes) {
  94496. for (var m in this._meshes) {
  94497. var mesh = this._meshes[m];
  94498. if (mesh) {
  94499. serializationObject.meshes.push({
  94500. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94501. color: mesh.color.asArray(),
  94502. meshId: mesh.mesh.id
  94503. });
  94504. }
  94505. }
  94506. }
  94507. // Excluded meshes
  94508. serializationObject.excludedMeshes = [];
  94509. if (this._excludedMeshes) {
  94510. for (var e in this._excludedMeshes) {
  94511. var excludedMesh = this._excludedMeshes[e];
  94512. if (excludedMesh) {
  94513. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94514. }
  94515. }
  94516. }
  94517. return serializationObject;
  94518. };
  94519. /**
  94520. * Creates a Highlight layer from parsed Highlight layer data
  94521. * @param parsedHightlightLayer defines the Highlight layer data
  94522. * @param scene defines the current scene
  94523. * @param rootUrl defines the root URL containing the Highlight layer information
  94524. * @returns a parsed Highlight layer
  94525. */
  94526. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94527. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94528. var index;
  94529. // Excluded meshes
  94530. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94531. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94532. if (mesh) {
  94533. hl.addExcludedMesh(mesh);
  94534. }
  94535. }
  94536. // Included meshes
  94537. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94538. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94539. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94540. if (mesh) {
  94541. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94542. }
  94543. }
  94544. return hl;
  94545. };
  94546. /**
  94547. * Effect Name of the highlight layer.
  94548. */
  94549. HighlightLayer.EffectName = "HighlightLayer";
  94550. /**
  94551. * The neutral color used during the preparation of the glow effect.
  94552. * This is black by default as the blend operation is a blend operation.
  94553. */
  94554. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94555. /**
  94556. * Stencil value used for glowing meshes.
  94557. */
  94558. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94559. /**
  94560. * Stencil value used for the other meshes in the scene.
  94561. */
  94562. HighlightLayer.NormalMeshStencilReference = 0x01;
  94563. __decorate([
  94564. BABYLON.serialize()
  94565. ], HighlightLayer.prototype, "innerGlow", void 0);
  94566. __decorate([
  94567. BABYLON.serialize()
  94568. ], HighlightLayer.prototype, "outerGlow", void 0);
  94569. __decorate([
  94570. BABYLON.serialize()
  94571. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94572. __decorate([
  94573. BABYLON.serialize()
  94574. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94575. __decorate([
  94576. BABYLON.serialize("options")
  94577. ], HighlightLayer.prototype, "_options", void 0);
  94578. return HighlightLayer;
  94579. }(BABYLON.EffectLayer));
  94580. BABYLON.HighlightLayer = HighlightLayer;
  94581. })(BABYLON || (BABYLON = {}));
  94582. //# sourceMappingURL=babylon.highlightLayer.js.map
  94583. var BABYLON;
  94584. (function (BABYLON) {
  94585. /**
  94586. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94587. *
  94588. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94589. * glowy meshes to your scene.
  94590. *
  94591. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94592. */
  94593. var GlowLayer = /** @class */ (function (_super) {
  94594. __extends(GlowLayer, _super);
  94595. /**
  94596. * Instantiates a new glow Layer and references it to the scene.
  94597. * @param name The name of the layer
  94598. * @param scene The scene to use the layer in
  94599. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94600. */
  94601. function GlowLayer(name, scene, options) {
  94602. var _this = _super.call(this, name, scene) || this;
  94603. _this._intensity = 1.0;
  94604. _this._includedOnlyMeshes = [];
  94605. _this._excludedMeshes = [];
  94606. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94607. // Adapt options
  94608. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94609. // Initialize the layer
  94610. _this._init({
  94611. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94612. camera: _this._options.camera,
  94613. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94614. mainTextureRatio: _this._options.mainTextureRatio
  94615. });
  94616. return _this;
  94617. }
  94618. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94619. /**
  94620. * Gets the kernel size of the blur.
  94621. */
  94622. get: function () {
  94623. return this._horizontalBlurPostprocess1.kernel;
  94624. },
  94625. /**
  94626. * Sets the kernel size of the blur.
  94627. */
  94628. set: function (value) {
  94629. this._horizontalBlurPostprocess1.kernel = value;
  94630. this._verticalBlurPostprocess1.kernel = value;
  94631. this._horizontalBlurPostprocess2.kernel = value;
  94632. this._verticalBlurPostprocess2.kernel = value;
  94633. },
  94634. enumerable: true,
  94635. configurable: true
  94636. });
  94637. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94638. /**
  94639. * Gets the glow intensity.
  94640. */
  94641. get: function () {
  94642. return this._intensity;
  94643. },
  94644. /**
  94645. * Sets the glow intensity.
  94646. */
  94647. set: function (value) {
  94648. this._intensity = value;
  94649. },
  94650. enumerable: true,
  94651. configurable: true
  94652. });
  94653. /**
  94654. * Get the effect name of the layer.
  94655. * @return The effect name
  94656. */
  94657. GlowLayer.prototype.getEffectName = function () {
  94658. return GlowLayer.EffectName;
  94659. };
  94660. /**
  94661. * Create the merge effect. This is the shader use to blit the information back
  94662. * to the main canvas at the end of the scene rendering.
  94663. */
  94664. GlowLayer.prototype._createMergeEffect = function () {
  94665. // Effect
  94666. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94667. };
  94668. /**
  94669. * Creates the render target textures and post processes used in the glow layer.
  94670. */
  94671. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94672. var _this = this;
  94673. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94674. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94675. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94676. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94677. var textureType = 0;
  94678. if (this._engine.getCaps().textureHalfFloatRender) {
  94679. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94680. }
  94681. else {
  94682. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94683. }
  94684. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94685. width: blurTextureWidth,
  94686. height: blurTextureHeight
  94687. }, this._scene, false, true, textureType);
  94688. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94689. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94690. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94691. this._blurTexture1.renderParticles = false;
  94692. this._blurTexture1.ignoreCameraViewport = true;
  94693. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94694. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94695. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94696. width: blurTextureWidth2,
  94697. height: blurTextureHeight2
  94698. }, this._scene, false, true, textureType);
  94699. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94700. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94701. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94702. this._blurTexture2.renderParticles = false;
  94703. this._blurTexture2.ignoreCameraViewport = true;
  94704. this._textures = [this._blurTexture1, this._blurTexture2];
  94705. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94706. width: blurTextureWidth,
  94707. height: blurTextureHeight
  94708. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94709. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94710. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94711. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94712. effect.setTexture("textureSampler", _this._mainTexture);
  94713. });
  94714. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94715. width: blurTextureWidth,
  94716. height: blurTextureHeight
  94717. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94718. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94719. width: blurTextureWidth2,
  94720. height: blurTextureHeight2
  94721. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94722. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94723. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94724. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94725. effect.setTexture("textureSampler", _this._blurTexture1);
  94726. });
  94727. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94728. width: blurTextureWidth2,
  94729. height: blurTextureHeight2
  94730. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94731. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94732. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94733. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94734. this._mainTexture.samples = this._options.mainTextureSamples;
  94735. this._mainTexture.onAfterUnbindObservable.add(function () {
  94736. var internalTexture = _this._blurTexture1.getInternalTexture();
  94737. if (internalTexture) {
  94738. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94739. internalTexture = _this._blurTexture2.getInternalTexture();
  94740. if (internalTexture) {
  94741. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94742. }
  94743. }
  94744. });
  94745. // Prevent autoClear.
  94746. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94747. };
  94748. /**
  94749. * Checks for the readiness of the element composing the layer.
  94750. * @param subMesh the mesh to check for
  94751. * @param useInstances specify wether or not to use instances to render the mesh
  94752. * @param emissiveTexture the associated emissive texture used to generate the glow
  94753. * @return true if ready otherwise, false
  94754. */
  94755. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94756. var material = subMesh.getMaterial();
  94757. var mesh = subMesh.getRenderingMesh();
  94758. if (!material || !mesh) {
  94759. return false;
  94760. }
  94761. var emissiveTexture = material.emissiveTexture;
  94762. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94763. };
  94764. /**
  94765. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94766. */
  94767. GlowLayer.prototype.needStencil = function () {
  94768. return false;
  94769. };
  94770. /**
  94771. * Implementation specific of rendering the generating effect on the main canvas.
  94772. * @param effect The effect used to render through
  94773. */
  94774. GlowLayer.prototype._internalRender = function (effect) {
  94775. // Texture
  94776. effect.setTexture("textureSampler", this._blurTexture1);
  94777. effect.setTexture("textureSampler2", this._blurTexture2);
  94778. effect.setFloat("offset", this._intensity);
  94779. // Cache
  94780. var engine = this._engine;
  94781. var previousStencilBuffer = engine.getStencilBuffer();
  94782. // Draw order
  94783. engine.setStencilBuffer(false);
  94784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94785. // Draw order
  94786. engine.setStencilBuffer(previousStencilBuffer);
  94787. };
  94788. /**
  94789. * Sets the required values for both the emissive texture and and the main color.
  94790. */
  94791. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94792. var textureLevel = 1.0;
  94793. if (this.customEmissiveTextureSelector) {
  94794. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94795. }
  94796. else {
  94797. if (material) {
  94798. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94799. if (this._emissiveTextureAndColor.texture) {
  94800. textureLevel = this._emissiveTextureAndColor.texture.level;
  94801. }
  94802. }
  94803. else {
  94804. this._emissiveTextureAndColor.texture = null;
  94805. }
  94806. }
  94807. if (this.customEmissiveColorSelector) {
  94808. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94809. }
  94810. else {
  94811. if (material.emissiveColor) {
  94812. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94813. }
  94814. else {
  94815. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94816. }
  94817. }
  94818. };
  94819. /**
  94820. * Returns true if the mesh should render, otherwise false.
  94821. * @param mesh The mesh to render
  94822. * @returns true if it should render otherwise false
  94823. */
  94824. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94825. return this.hasMesh(mesh);
  94826. };
  94827. /**
  94828. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94829. * @param mesh The mesh to exclude from the glow layer
  94830. */
  94831. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94832. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94833. this._excludedMeshes.push(mesh.uniqueId);
  94834. }
  94835. };
  94836. /**
  94837. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94838. * @param mesh The mesh to remove
  94839. */
  94840. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94841. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94842. if (index !== -1) {
  94843. this._excludedMeshes.splice(index, 1);
  94844. }
  94845. };
  94846. /**
  94847. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94848. * @param mesh The mesh to include in the glow layer
  94849. */
  94850. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94851. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94852. this._includedOnlyMeshes.push(mesh.uniqueId);
  94853. }
  94854. };
  94855. /**
  94856. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94857. * @param mesh The mesh to remove
  94858. */
  94859. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94860. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94861. if (index !== -1) {
  94862. this._includedOnlyMeshes.splice(index, 1);
  94863. }
  94864. };
  94865. /**
  94866. * Determine if a given mesh will be used in the glow layer
  94867. * @param mesh The mesh to test
  94868. * @returns true if the mesh will be highlighted by the current glow layer
  94869. */
  94870. GlowLayer.prototype.hasMesh = function (mesh) {
  94871. // Included Mesh
  94872. if (this._includedOnlyMeshes.length) {
  94873. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94874. }
  94875. ;
  94876. // Excluded Mesh
  94877. if (this._excludedMeshes.length) {
  94878. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94879. }
  94880. ;
  94881. return true;
  94882. };
  94883. /**
  94884. * Free any resources and references associated to a mesh.
  94885. * Internal use
  94886. * @param mesh The mesh to free.
  94887. */
  94888. GlowLayer.prototype._disposeMesh = function (mesh) {
  94889. this.removeIncludedOnlyMesh(mesh);
  94890. this.removeExcludedMesh(mesh);
  94891. };
  94892. /**
  94893. * Gets the class name of the effect layer
  94894. * @returns the string with the class name of the effect layer
  94895. */
  94896. GlowLayer.prototype.getClassName = function () {
  94897. return "GlowLayer";
  94898. };
  94899. /**
  94900. * Serializes this glow layer
  94901. * @returns a serialized glow layer object
  94902. */
  94903. GlowLayer.prototype.serialize = function () {
  94904. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94905. serializationObject.customType = "BABYLON.GlowLayer";
  94906. var index;
  94907. // Included meshes
  94908. serializationObject.includedMeshes = [];
  94909. if (this._includedOnlyMeshes.length) {
  94910. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94911. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94912. if (mesh) {
  94913. serializationObject.includedMeshes.push(mesh.id);
  94914. }
  94915. }
  94916. }
  94917. // Excluded meshes
  94918. serializationObject.excludedMeshes = [];
  94919. if (this._excludedMeshes.length) {
  94920. for (index = 0; index < this._excludedMeshes.length; index++) {
  94921. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94922. if (mesh) {
  94923. serializationObject.excludedMeshes.push(mesh.id);
  94924. }
  94925. }
  94926. }
  94927. return serializationObject;
  94928. };
  94929. /**
  94930. * Creates a Glow Layer from parsed glow layer data
  94931. * @param parsedGlowLayer defines glow layer data
  94932. * @param scene defines the current scene
  94933. * @param rootUrl defines the root URL containing the glow layer information
  94934. * @returns a parsed Glow Layer
  94935. */
  94936. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94937. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94938. var index;
  94939. // Excluded meshes
  94940. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94941. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94942. if (mesh) {
  94943. gl.addExcludedMesh(mesh);
  94944. }
  94945. }
  94946. // Included meshes
  94947. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94948. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94949. if (mesh) {
  94950. gl.addIncludedOnlyMesh(mesh);
  94951. }
  94952. }
  94953. return gl;
  94954. };
  94955. /**
  94956. * Effect Name of the layer.
  94957. */
  94958. GlowLayer.EffectName = "GlowLayer";
  94959. /**
  94960. * The default blur kernel size used for the glow.
  94961. */
  94962. GlowLayer.DefaultBlurKernelSize = 32;
  94963. /**
  94964. * The default texture size ratio used for the glow.
  94965. */
  94966. GlowLayer.DefaultTextureRatio = 0.5;
  94967. __decorate([
  94968. BABYLON.serialize()
  94969. ], GlowLayer.prototype, "blurKernelSize", null);
  94970. __decorate([
  94971. BABYLON.serialize()
  94972. ], GlowLayer.prototype, "intensity", null);
  94973. __decorate([
  94974. BABYLON.serialize("options")
  94975. ], GlowLayer.prototype, "_options", void 0);
  94976. return GlowLayer;
  94977. }(BABYLON.EffectLayer));
  94978. BABYLON.GlowLayer = GlowLayer;
  94979. })(BABYLON || (BABYLON = {}));
  94980. //# sourceMappingURL=babylon.glowLayer.js.map
  94981. var BABYLON;
  94982. (function (BABYLON) {
  94983. /**
  94984. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  94985. */
  94986. var AssetTaskState;
  94987. (function (AssetTaskState) {
  94988. /**
  94989. * Initialization
  94990. */
  94991. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  94992. /**
  94993. * Running
  94994. */
  94995. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  94996. /**
  94997. * Done
  94998. */
  94999. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95000. /**
  95001. * Error
  95002. */
  95003. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95004. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95005. /**
  95006. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95007. */
  95008. var AbstractAssetTask = /** @class */ (function () {
  95009. /**
  95010. * Creates a new {BABYLON.AssetsManager}
  95011. * @param name defines the name of the task
  95012. */
  95013. function AbstractAssetTask(
  95014. /**
  95015. * Task name
  95016. */ name) {
  95017. this.name = name;
  95018. this._isCompleted = false;
  95019. this._taskState = AssetTaskState.INIT;
  95020. }
  95021. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95022. /**
  95023. * Get if the task is completed
  95024. */
  95025. get: function () {
  95026. return this._isCompleted;
  95027. },
  95028. enumerable: true,
  95029. configurable: true
  95030. });
  95031. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95032. /**
  95033. * Gets the current state of the task
  95034. */
  95035. get: function () {
  95036. return this._taskState;
  95037. },
  95038. enumerable: true,
  95039. configurable: true
  95040. });
  95041. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95042. /**
  95043. * Gets the current error object (if task is in error)
  95044. */
  95045. get: function () {
  95046. return this._errorObject;
  95047. },
  95048. enumerable: true,
  95049. configurable: true
  95050. });
  95051. /**
  95052. * Internal only
  95053. * @hidden
  95054. */
  95055. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95056. if (this._errorObject) {
  95057. return;
  95058. }
  95059. this._errorObject = {
  95060. message: message,
  95061. exception: exception
  95062. };
  95063. };
  95064. /**
  95065. * Execute the current task
  95066. * @param scene defines the scene where you want your assets to be loaded
  95067. * @param onSuccess is a callback called when the task is successfully executed
  95068. * @param onError is a callback called if an error occurs
  95069. */
  95070. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95071. var _this = this;
  95072. this._taskState = AssetTaskState.RUNNING;
  95073. this.runTask(scene, function () {
  95074. _this.onDoneCallback(onSuccess, onError);
  95075. }, function (msg, exception) {
  95076. _this.onErrorCallback(onError, msg, exception);
  95077. });
  95078. };
  95079. /**
  95080. * Execute the current task
  95081. * @param scene defines the scene where you want your assets to be loaded
  95082. * @param onSuccess is a callback called when the task is successfully executed
  95083. * @param onError is a callback called if an error occurs
  95084. */
  95085. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95086. throw new Error("runTask is not implemented");
  95087. };
  95088. /**
  95089. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95090. * This can be used with failed tasks that have the reason for failure fixed.
  95091. */
  95092. AbstractAssetTask.prototype.reset = function () {
  95093. this._taskState = AssetTaskState.INIT;
  95094. };
  95095. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95096. this._taskState = AssetTaskState.ERROR;
  95097. this._errorObject = {
  95098. message: message,
  95099. exception: exception
  95100. };
  95101. if (this.onError) {
  95102. this.onError(this, message, exception);
  95103. }
  95104. onError();
  95105. };
  95106. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95107. try {
  95108. this._taskState = AssetTaskState.DONE;
  95109. this._isCompleted = true;
  95110. if (this.onSuccess) {
  95111. this.onSuccess(this);
  95112. }
  95113. onSuccess();
  95114. }
  95115. catch (e) {
  95116. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95117. }
  95118. };
  95119. return AbstractAssetTask;
  95120. }());
  95121. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95122. /**
  95123. * Class used to share progress information about assets loading
  95124. */
  95125. var AssetsProgressEvent = /** @class */ (function () {
  95126. /**
  95127. * Creates a {BABYLON.AssetsProgressEvent}
  95128. * @param remainingCount defines the number of remaining tasks to process
  95129. * @param totalCount defines the total number of tasks
  95130. * @param task defines the task that was just processed
  95131. */
  95132. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95133. this.remainingCount = remainingCount;
  95134. this.totalCount = totalCount;
  95135. this.task = task;
  95136. }
  95137. return AssetsProgressEvent;
  95138. }());
  95139. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95140. /**
  95141. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95142. */
  95143. var MeshAssetTask = /** @class */ (function (_super) {
  95144. __extends(MeshAssetTask, _super);
  95145. /**
  95146. * Creates a new {BABYLON.MeshAssetTask}
  95147. * @param name defines the name of the task
  95148. * @param meshesNames defines the list of mesh's names you want to load
  95149. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95150. * @param sceneFilename defines the filename of the scene to load from
  95151. */
  95152. function MeshAssetTask(
  95153. /**
  95154. * Defines the name of the task
  95155. */
  95156. name,
  95157. /**
  95158. * Defines the list of mesh's names you want to load
  95159. */
  95160. meshesNames,
  95161. /**
  95162. * Defines the root url to use as a base to load your meshes and associated resources
  95163. */
  95164. rootUrl,
  95165. /**
  95166. * Defines the filename of the scene to load from
  95167. */
  95168. sceneFilename) {
  95169. var _this = _super.call(this, name) || this;
  95170. _this.name = name;
  95171. _this.meshesNames = meshesNames;
  95172. _this.rootUrl = rootUrl;
  95173. _this.sceneFilename = sceneFilename;
  95174. return _this;
  95175. }
  95176. /**
  95177. * Execute the current task
  95178. * @param scene defines the scene where you want your assets to be loaded
  95179. * @param onSuccess is a callback called when the task is successfully executed
  95180. * @param onError is a callback called if an error occurs
  95181. */
  95182. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95183. var _this = this;
  95184. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95185. _this.loadedMeshes = meshes;
  95186. _this.loadedParticleSystems = particleSystems;
  95187. _this.loadedSkeletons = skeletons;
  95188. onSuccess();
  95189. }, null, function (scene, message, exception) {
  95190. onError(message, exception);
  95191. });
  95192. };
  95193. return MeshAssetTask;
  95194. }(AbstractAssetTask));
  95195. BABYLON.MeshAssetTask = MeshAssetTask;
  95196. /**
  95197. * Define a task used by {BABYLON.AssetsManager} to load text content
  95198. */
  95199. var TextFileAssetTask = /** @class */ (function (_super) {
  95200. __extends(TextFileAssetTask, _super);
  95201. /**
  95202. * Creates a new TextFileAssetTask object
  95203. * @param name defines the name of the task
  95204. * @param url defines the location of the file to load
  95205. */
  95206. function TextFileAssetTask(
  95207. /**
  95208. * Defines the name of the task
  95209. */
  95210. name,
  95211. /**
  95212. * Defines the location of the file to load
  95213. */
  95214. url) {
  95215. var _this = _super.call(this, name) || this;
  95216. _this.name = name;
  95217. _this.url = url;
  95218. return _this;
  95219. }
  95220. /**
  95221. * Execute the current task
  95222. * @param scene defines the scene where you want your assets to be loaded
  95223. * @param onSuccess is a callback called when the task is successfully executed
  95224. * @param onError is a callback called if an error occurs
  95225. */
  95226. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95227. var _this = this;
  95228. scene._loadFile(this.url, function (data) {
  95229. _this.text = data;
  95230. onSuccess();
  95231. }, undefined, false, false, function (request, exception) {
  95232. if (request) {
  95233. onError(request.status + " " + request.statusText, exception);
  95234. }
  95235. });
  95236. };
  95237. return TextFileAssetTask;
  95238. }(AbstractAssetTask));
  95239. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95240. /**
  95241. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95242. */
  95243. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95244. __extends(BinaryFileAssetTask, _super);
  95245. /**
  95246. * Creates a new BinaryFileAssetTask object
  95247. * @param name defines the name of the new task
  95248. * @param url defines the location of the file to load
  95249. */
  95250. function BinaryFileAssetTask(
  95251. /**
  95252. * Defines the name of the task
  95253. */
  95254. name,
  95255. /**
  95256. * Defines the location of the file to load
  95257. */
  95258. url) {
  95259. var _this = _super.call(this, name) || this;
  95260. _this.name = name;
  95261. _this.url = url;
  95262. return _this;
  95263. }
  95264. /**
  95265. * Execute the current task
  95266. * @param scene defines the scene where you want your assets to be loaded
  95267. * @param onSuccess is a callback called when the task is successfully executed
  95268. * @param onError is a callback called if an error occurs
  95269. */
  95270. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95271. var _this = this;
  95272. scene._loadFile(this.url, function (data) {
  95273. _this.data = data;
  95274. onSuccess();
  95275. }, undefined, true, true, function (request, exception) {
  95276. if (request) {
  95277. onError(request.status + " " + request.statusText, exception);
  95278. }
  95279. });
  95280. };
  95281. return BinaryFileAssetTask;
  95282. }(AbstractAssetTask));
  95283. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95284. /**
  95285. * Define a task used by {BABYLON.AssetsManager} to load images
  95286. */
  95287. var ImageAssetTask = /** @class */ (function (_super) {
  95288. __extends(ImageAssetTask, _super);
  95289. /**
  95290. * Creates a new ImageAssetTask
  95291. * @param name defines the name of the task
  95292. * @param url defines the location of the image to load
  95293. */
  95294. function ImageAssetTask(
  95295. /**
  95296. * Defines the name of the task
  95297. */
  95298. name,
  95299. /**
  95300. * Defines the location of the image to load
  95301. */
  95302. url) {
  95303. var _this = _super.call(this, name) || this;
  95304. _this.name = name;
  95305. _this.url = url;
  95306. return _this;
  95307. }
  95308. /**
  95309. * Execute the current task
  95310. * @param scene defines the scene where you want your assets to be loaded
  95311. * @param onSuccess is a callback called when the task is successfully executed
  95312. * @param onError is a callback called if an error occurs
  95313. */
  95314. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95315. var _this = this;
  95316. var img = new Image();
  95317. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95318. img.onload = function () {
  95319. _this.image = img;
  95320. onSuccess();
  95321. };
  95322. img.onerror = function (err) {
  95323. onError("Error loading image", err);
  95324. };
  95325. img.src = this.url;
  95326. };
  95327. return ImageAssetTask;
  95328. }(AbstractAssetTask));
  95329. BABYLON.ImageAssetTask = ImageAssetTask;
  95330. /**
  95331. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95332. */
  95333. var TextureAssetTask = /** @class */ (function (_super) {
  95334. __extends(TextureAssetTask, _super);
  95335. /**
  95336. * Creates a new TextureAssetTask object
  95337. * @param name defines the name of the task
  95338. * @param url defines the location of the file to load
  95339. * @param noMipmap defines if mipmap should not be generated (default is false)
  95340. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95341. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95342. */
  95343. function TextureAssetTask(
  95344. /**
  95345. * Defines the name of the task
  95346. */
  95347. name,
  95348. /**
  95349. * Defines the location of the file to load
  95350. */
  95351. url,
  95352. /**
  95353. * Defines if mipmap should not be generated (default is false)
  95354. */
  95355. noMipmap,
  95356. /**
  95357. * Defines if texture must be inverted on Y axis (default is false)
  95358. */
  95359. invertY,
  95360. /**
  95361. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95362. */
  95363. samplingMode) {
  95364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95365. var _this = _super.call(this, name) || this;
  95366. _this.name = name;
  95367. _this.url = url;
  95368. _this.noMipmap = noMipmap;
  95369. _this.invertY = invertY;
  95370. _this.samplingMode = samplingMode;
  95371. return _this;
  95372. }
  95373. /**
  95374. * Execute the current task
  95375. * @param scene defines the scene where you want your assets to be loaded
  95376. * @param onSuccess is a callback called when the task is successfully executed
  95377. * @param onError is a callback called if an error occurs
  95378. */
  95379. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95380. var onload = function () {
  95381. onSuccess();
  95382. };
  95383. var onerror = function (message, exception) {
  95384. onError(message, exception);
  95385. };
  95386. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95387. };
  95388. return TextureAssetTask;
  95389. }(AbstractAssetTask));
  95390. BABYLON.TextureAssetTask = TextureAssetTask;
  95391. /**
  95392. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95393. */
  95394. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95395. __extends(CubeTextureAssetTask, _super);
  95396. /**
  95397. * Creates a new CubeTextureAssetTask
  95398. * @param name defines the name of the task
  95399. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95400. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95401. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95402. * @param files defines the explicit list of files (undefined by default)
  95403. */
  95404. function CubeTextureAssetTask(
  95405. /**
  95406. * Defines the name of the task
  95407. */
  95408. name,
  95409. /**
  95410. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95411. */
  95412. url,
  95413. /**
  95414. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95415. */
  95416. extensions,
  95417. /**
  95418. * Defines if mipmaps should not be generated (default is false)
  95419. */
  95420. noMipmap,
  95421. /**
  95422. * Defines the explicit list of files (undefined by default)
  95423. */
  95424. files) {
  95425. var _this = _super.call(this, name) || this;
  95426. _this.name = name;
  95427. _this.url = url;
  95428. _this.extensions = extensions;
  95429. _this.noMipmap = noMipmap;
  95430. _this.files = files;
  95431. return _this;
  95432. }
  95433. /**
  95434. * Execute the current task
  95435. * @param scene defines the scene where you want your assets to be loaded
  95436. * @param onSuccess is a callback called when the task is successfully executed
  95437. * @param onError is a callback called if an error occurs
  95438. */
  95439. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95440. var onload = function () {
  95441. onSuccess();
  95442. };
  95443. var onerror = function (message, exception) {
  95444. onError(message, exception);
  95445. };
  95446. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95447. };
  95448. return CubeTextureAssetTask;
  95449. }(AbstractAssetTask));
  95450. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95451. /**
  95452. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95453. */
  95454. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95455. __extends(HDRCubeTextureAssetTask, _super);
  95456. /**
  95457. * Creates a new HDRCubeTextureAssetTask object
  95458. * @param name defines the name of the task
  95459. * @param url defines the location of the file to load
  95460. * @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.
  95461. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95462. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95463. * @param gammaSpace 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)
  95464. * @param reserved Internal use only
  95465. */
  95466. function HDRCubeTextureAssetTask(
  95467. /**
  95468. * Defines the name of the task
  95469. */
  95470. name,
  95471. /**
  95472. * Defines the location of the file to load
  95473. */
  95474. url,
  95475. /**
  95476. * Defines the desired size (the more it increases the longer the generation will be)
  95477. */
  95478. size,
  95479. /**
  95480. * Defines if mipmaps should not be generated (default is false)
  95481. */
  95482. noMipmap,
  95483. /**
  95484. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95485. */
  95486. generateHarmonics,
  95487. /**
  95488. * 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)
  95489. */
  95490. gammaSpace,
  95491. /**
  95492. * Internal Use Only
  95493. */
  95494. reserved) {
  95495. if (noMipmap === void 0) { noMipmap = false; }
  95496. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95497. if (gammaSpace === void 0) { gammaSpace = false; }
  95498. if (reserved === void 0) { reserved = false; }
  95499. var _this = _super.call(this, name) || this;
  95500. _this.name = name;
  95501. _this.url = url;
  95502. _this.size = size;
  95503. _this.noMipmap = noMipmap;
  95504. _this.generateHarmonics = generateHarmonics;
  95505. _this.gammaSpace = gammaSpace;
  95506. _this.reserved = reserved;
  95507. return _this;
  95508. }
  95509. /**
  95510. * Execute the current task
  95511. * @param scene defines the scene where you want your assets to be loaded
  95512. * @param onSuccess is a callback called when the task is successfully executed
  95513. * @param onError is a callback called if an error occurs
  95514. */
  95515. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95516. var onload = function () {
  95517. onSuccess();
  95518. };
  95519. var onerror = function (message, exception) {
  95520. onError(message, exception);
  95521. };
  95522. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95523. };
  95524. return HDRCubeTextureAssetTask;
  95525. }(AbstractAssetTask));
  95526. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95527. /**
  95528. * This class can be used to easily import assets into a scene
  95529. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95530. */
  95531. var AssetsManager = /** @class */ (function () {
  95532. /**
  95533. * Creates a new AssetsManager
  95534. * @param scene defines the scene to work on
  95535. */
  95536. function AssetsManager(scene) {
  95537. this._isLoading = false;
  95538. this._tasks = new Array();
  95539. this._waitingTasksCount = 0;
  95540. this._totalTasksCount = 0;
  95541. /**
  95542. * Observable called when all tasks are processed
  95543. */
  95544. this.onTaskSuccessObservable = new BABYLON.Observable();
  95545. /**
  95546. * Observable called when a task had an error
  95547. */
  95548. this.onTaskErrorObservable = new BABYLON.Observable();
  95549. /**
  95550. * Observable called when a task is successful
  95551. */
  95552. this.onTasksDoneObservable = new BABYLON.Observable();
  95553. /**
  95554. * Observable called when a task is done (whatever the result is)
  95555. */
  95556. this.onProgressObservable = new BABYLON.Observable();
  95557. /**
  95558. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95559. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95560. */
  95561. this.useDefaultLoadingScreen = true;
  95562. this._scene = scene;
  95563. }
  95564. /**
  95565. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95566. * @param taskName defines the name of the new task
  95567. * @param meshesNames defines the name of meshes to load
  95568. * @param rootUrl defines the root url to use to locate files
  95569. * @param sceneFilename defines the filename of the scene file
  95570. * @returns a new {BABYLON.MeshAssetTask} object
  95571. */
  95572. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95573. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95574. this._tasks.push(task);
  95575. return task;
  95576. };
  95577. /**
  95578. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95579. * @param taskName defines the name of the new task
  95580. * @param url defines the url of the file to load
  95581. * @returns a new {BABYLON.TextFileAssetTask} object
  95582. */
  95583. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95584. var task = new TextFileAssetTask(taskName, url);
  95585. this._tasks.push(task);
  95586. return task;
  95587. };
  95588. /**
  95589. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95590. * @param taskName defines the name of the new task
  95591. * @param url defines the url of the file to load
  95592. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95593. */
  95594. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95595. var task = new BinaryFileAssetTask(taskName, url);
  95596. this._tasks.push(task);
  95597. return task;
  95598. };
  95599. /**
  95600. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95601. * @param taskName defines the name of the new task
  95602. * @param url defines the url of the file to load
  95603. * @returns a new {BABYLON.ImageAssetTask} object
  95604. */
  95605. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95606. var task = new ImageAssetTask(taskName, url);
  95607. this._tasks.push(task);
  95608. return task;
  95609. };
  95610. /**
  95611. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95612. * @param taskName defines the name of the new task
  95613. * @param url defines the url of the file to load
  95614. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95615. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95616. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95617. * @returns a new {BABYLON.TextureAssetTask} object
  95618. */
  95619. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95621. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95622. this._tasks.push(task);
  95623. return task;
  95624. };
  95625. /**
  95626. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95627. * @param taskName defines the name of the new task
  95628. * @param url defines the url of the file to load
  95629. * @param extensions defines the extension to use to load the cube map (can be null)
  95630. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95631. * @param files defines the list of files to load (can be null)
  95632. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95633. */
  95634. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95635. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95636. this._tasks.push(task);
  95637. return task;
  95638. };
  95639. /**
  95640. *
  95641. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95642. * @param taskName defines the name of the new task
  95643. * @param url defines the url of the file to load
  95644. * @param size defines the size you want for the cubemap (can be null)
  95645. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95646. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95647. * @param gammaSpace 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)
  95648. * @param reserved Internal use only
  95649. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95650. */
  95651. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95652. if (noMipmap === void 0) { noMipmap = false; }
  95653. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95654. if (gammaSpace === void 0) { gammaSpace = false; }
  95655. if (reserved === void 0) { reserved = false; }
  95656. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95657. this._tasks.push(task);
  95658. return task;
  95659. };
  95660. /**
  95661. * Remove a task from the assets manager.
  95662. * @param task the task to remove
  95663. */
  95664. AssetsManager.prototype.removeTask = function (task) {
  95665. var index = this._tasks.indexOf(task);
  95666. if (index > -1) {
  95667. this._tasks.splice(index, 1);
  95668. }
  95669. };
  95670. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95671. this._waitingTasksCount--;
  95672. try {
  95673. if (this.onProgress) {
  95674. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95675. }
  95676. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95677. }
  95678. catch (e) {
  95679. BABYLON.Tools.Error("Error running progress callbacks.");
  95680. console.log(e);
  95681. }
  95682. if (this._waitingTasksCount === 0) {
  95683. try {
  95684. if (this.onFinish) {
  95685. this.onFinish(this._tasks);
  95686. }
  95687. // Let's remove successfull tasks
  95688. var currentTasks = this._tasks.slice();
  95689. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95690. var task = currentTasks_1[_i];
  95691. if (task.taskState === AssetTaskState.DONE) {
  95692. var index = this._tasks.indexOf(task);
  95693. if (index > -1) {
  95694. this._tasks.splice(index, 1);
  95695. }
  95696. }
  95697. }
  95698. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95699. }
  95700. catch (e) {
  95701. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95702. console.log(e);
  95703. }
  95704. this._isLoading = false;
  95705. this._scene.getEngine().hideLoadingUI();
  95706. }
  95707. };
  95708. AssetsManager.prototype._runTask = function (task) {
  95709. var _this = this;
  95710. var done = function () {
  95711. try {
  95712. if (_this.onTaskSuccess) {
  95713. _this.onTaskSuccess(task);
  95714. }
  95715. _this.onTaskSuccessObservable.notifyObservers(task);
  95716. _this._decreaseWaitingTasksCount(task);
  95717. }
  95718. catch (e) {
  95719. error("Error executing task success callbacks", e);
  95720. }
  95721. };
  95722. var error = function (message, exception) {
  95723. task._setErrorObject(message, exception);
  95724. if (_this.onTaskError) {
  95725. _this.onTaskError(task);
  95726. }
  95727. _this.onTaskErrorObservable.notifyObservers(task);
  95728. _this._decreaseWaitingTasksCount(task);
  95729. };
  95730. task.run(this._scene, done, error);
  95731. };
  95732. /**
  95733. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95734. * @return the current instance of the {BABYLON.AssetsManager}
  95735. */
  95736. AssetsManager.prototype.reset = function () {
  95737. this._isLoading = false;
  95738. this._tasks = new Array();
  95739. return this;
  95740. };
  95741. /**
  95742. * Start the loading process
  95743. * @return the current instance of the {BABYLON.AssetsManager}
  95744. */
  95745. AssetsManager.prototype.load = function () {
  95746. if (this._isLoading) {
  95747. return this;
  95748. }
  95749. this._isLoading = true;
  95750. this._waitingTasksCount = this._tasks.length;
  95751. this._totalTasksCount = this._tasks.length;
  95752. if (this._waitingTasksCount === 0) {
  95753. this._isLoading = false;
  95754. if (this.onFinish) {
  95755. this.onFinish(this._tasks);
  95756. }
  95757. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95758. return this;
  95759. }
  95760. if (this.useDefaultLoadingScreen) {
  95761. this._scene.getEngine().displayLoadingUI();
  95762. }
  95763. for (var index = 0; index < this._tasks.length; index++) {
  95764. var task = this._tasks[index];
  95765. if (task.taskState === AssetTaskState.INIT) {
  95766. this._runTask(task);
  95767. }
  95768. }
  95769. return this;
  95770. };
  95771. return AssetsManager;
  95772. }());
  95773. BABYLON.AssetsManager = AssetsManager;
  95774. })(BABYLON || (BABYLON = {}));
  95775. //# sourceMappingURL=babylon.assetsManager.js.map
  95776. var BABYLON;
  95777. (function (BABYLON) {
  95778. var serializedGeometries = [];
  95779. var serializeGeometry = function (geometry, serializationGeometries) {
  95780. if (serializedGeometries[geometry.id]) {
  95781. return;
  95782. }
  95783. if (geometry.doNotSerialize) {
  95784. return;
  95785. }
  95786. if (geometry instanceof BABYLON.BoxGeometry) {
  95787. serializationGeometries.boxes.push(geometry.serialize());
  95788. }
  95789. else if (geometry instanceof BABYLON.SphereGeometry) {
  95790. serializationGeometries.spheres.push(geometry.serialize());
  95791. }
  95792. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95793. serializationGeometries.cylinders.push(geometry.serialize());
  95794. }
  95795. else if (geometry instanceof BABYLON.TorusGeometry) {
  95796. serializationGeometries.toruses.push(geometry.serialize());
  95797. }
  95798. else if (geometry instanceof BABYLON.GroundGeometry) {
  95799. serializationGeometries.grounds.push(geometry.serialize());
  95800. }
  95801. else if (geometry instanceof BABYLON.Plane) {
  95802. serializationGeometries.planes.push(geometry.serialize());
  95803. }
  95804. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95805. serializationGeometries.torusKnots.push(geometry.serialize());
  95806. }
  95807. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95808. throw new Error("Unknown primitive type");
  95809. }
  95810. else {
  95811. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95812. }
  95813. serializedGeometries[geometry.id] = true;
  95814. };
  95815. var serializeMesh = function (mesh, serializationScene) {
  95816. var serializationObject = {};
  95817. // Geometry
  95818. var geometry = mesh._geometry;
  95819. if (geometry) {
  95820. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95821. // 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
  95822. serializeGeometry(geometry, serializationScene.geometries);
  95823. }
  95824. }
  95825. // Custom
  95826. if (mesh.serialize) {
  95827. mesh.serialize(serializationObject);
  95828. }
  95829. return serializationObject;
  95830. };
  95831. var finalizeSingleMesh = function (mesh, serializationObject) {
  95832. //only works if the mesh is already loaded
  95833. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95834. //serialize material
  95835. if (mesh.material) {
  95836. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95837. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95838. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95839. serializationObject.multiMaterials.push(mesh.material.serialize());
  95840. }
  95841. }
  95842. else {
  95843. serializationObject.materials = serializationObject.materials || [];
  95844. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95845. serializationObject.materials.push(mesh.material.serialize());
  95846. }
  95847. }
  95848. }
  95849. //serialize geometry
  95850. var geometry = mesh._geometry;
  95851. if (geometry) {
  95852. if (!serializationObject.geometries) {
  95853. serializationObject.geometries = {};
  95854. serializationObject.geometries.boxes = [];
  95855. serializationObject.geometries.spheres = [];
  95856. serializationObject.geometries.cylinders = [];
  95857. serializationObject.geometries.toruses = [];
  95858. serializationObject.geometries.grounds = [];
  95859. serializationObject.geometries.planes = [];
  95860. serializationObject.geometries.torusKnots = [];
  95861. serializationObject.geometries.vertexData = [];
  95862. }
  95863. serializeGeometry(geometry, serializationObject.geometries);
  95864. }
  95865. // Skeletons
  95866. if (mesh.skeleton) {
  95867. serializationObject.skeletons = serializationObject.skeletons || [];
  95868. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95869. }
  95870. //serialize the actual mesh
  95871. serializationObject.meshes = serializationObject.meshes || [];
  95872. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95873. }
  95874. };
  95875. var SceneSerializer = /** @class */ (function () {
  95876. function SceneSerializer() {
  95877. }
  95878. SceneSerializer.ClearCache = function () {
  95879. serializedGeometries = [];
  95880. };
  95881. SceneSerializer.Serialize = function (scene) {
  95882. var serializationObject = {};
  95883. SceneSerializer.ClearCache();
  95884. // Scene
  95885. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95886. serializationObject.autoClear = scene.autoClear;
  95887. serializationObject.clearColor = scene.clearColor.asArray();
  95888. serializationObject.ambientColor = scene.ambientColor.asArray();
  95889. serializationObject.gravity = scene.gravity.asArray();
  95890. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95891. serializationObject.workerCollisions = scene.workerCollisions;
  95892. // Fog
  95893. if (scene.fogMode && scene.fogMode !== 0) {
  95894. serializationObject.fogMode = scene.fogMode;
  95895. serializationObject.fogColor = scene.fogColor.asArray();
  95896. serializationObject.fogStart = scene.fogStart;
  95897. serializationObject.fogEnd = scene.fogEnd;
  95898. serializationObject.fogDensity = scene.fogDensity;
  95899. }
  95900. //Physics
  95901. if (scene.isPhysicsEnabled()) {
  95902. var physicEngine = scene.getPhysicsEngine();
  95903. if (physicEngine) {
  95904. serializationObject.physicsEnabled = true;
  95905. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95906. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95907. }
  95908. }
  95909. // Metadata
  95910. if (scene.metadata) {
  95911. serializationObject.metadata = scene.metadata;
  95912. }
  95913. // Morph targets
  95914. serializationObject.morphTargetManagers = [];
  95915. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95916. var abstractMesh = _a[_i];
  95917. var manager = abstractMesh.morphTargetManager;
  95918. if (manager) {
  95919. serializationObject.morphTargetManagers.push(manager.serialize());
  95920. }
  95921. }
  95922. // Lights
  95923. serializationObject.lights = [];
  95924. var index;
  95925. var light;
  95926. for (index = 0; index < scene.lights.length; index++) {
  95927. light = scene.lights[index];
  95928. if (!light.doNotSerialize) {
  95929. serializationObject.lights.push(light.serialize());
  95930. }
  95931. }
  95932. // Cameras
  95933. serializationObject.cameras = [];
  95934. for (index = 0; index < scene.cameras.length; index++) {
  95935. var camera = scene.cameras[index];
  95936. if (!camera.doNotSerialize) {
  95937. serializationObject.cameras.push(camera.serialize());
  95938. }
  95939. }
  95940. if (scene.activeCamera) {
  95941. serializationObject.activeCameraID = scene.activeCamera.id;
  95942. }
  95943. // Animations
  95944. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95945. // Materials
  95946. serializationObject.materials = [];
  95947. serializationObject.multiMaterials = [];
  95948. var material;
  95949. for (index = 0; index < scene.materials.length; index++) {
  95950. material = scene.materials[index];
  95951. if (!material.doNotSerialize) {
  95952. serializationObject.materials.push(material.serialize());
  95953. }
  95954. }
  95955. // MultiMaterials
  95956. serializationObject.multiMaterials = [];
  95957. for (index = 0; index < scene.multiMaterials.length; index++) {
  95958. var multiMaterial = scene.multiMaterials[index];
  95959. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95960. }
  95961. // Environment texture
  95962. if (scene.environmentTexture) {
  95963. serializationObject.environmentTexture = scene.environmentTexture.name;
  95964. }
  95965. // Skeletons
  95966. serializationObject.skeletons = [];
  95967. for (index = 0; index < scene.skeletons.length; index++) {
  95968. var skeleton = scene.skeletons[index];
  95969. if (!skeleton.doNotSerialize) {
  95970. serializationObject.skeletons.push(skeleton.serialize());
  95971. }
  95972. }
  95973. // Transform nodes
  95974. serializationObject.transformNodes = [];
  95975. for (index = 0; index < scene.transformNodes.length; index++) {
  95976. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  95977. }
  95978. // Geometries
  95979. serializationObject.geometries = {};
  95980. serializationObject.geometries.boxes = [];
  95981. serializationObject.geometries.spheres = [];
  95982. serializationObject.geometries.cylinders = [];
  95983. serializationObject.geometries.toruses = [];
  95984. serializationObject.geometries.grounds = [];
  95985. serializationObject.geometries.planes = [];
  95986. serializationObject.geometries.torusKnots = [];
  95987. serializationObject.geometries.vertexData = [];
  95988. serializedGeometries = [];
  95989. var geometries = scene.getGeometries();
  95990. for (index = 0; index < geometries.length; index++) {
  95991. var geometry = geometries[index];
  95992. if (geometry.isReady()) {
  95993. serializeGeometry(geometry, serializationObject.geometries);
  95994. }
  95995. }
  95996. // Meshes
  95997. serializationObject.meshes = [];
  95998. for (index = 0; index < scene.meshes.length; index++) {
  95999. var abstractMesh = scene.meshes[index];
  96000. if (abstractMesh instanceof BABYLON.Mesh) {
  96001. var mesh = abstractMesh;
  96002. if (!mesh.doNotSerialize) {
  96003. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96004. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96005. }
  96006. }
  96007. }
  96008. }
  96009. // Particles Systems
  96010. serializationObject.particleSystems = [];
  96011. for (index = 0; index < scene.particleSystems.length; index++) {
  96012. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96013. }
  96014. // Lens flares
  96015. serializationObject.lensFlareSystems = [];
  96016. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96017. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96018. }
  96019. // Shadows
  96020. serializationObject.shadowGenerators = [];
  96021. for (index = 0; index < scene.lights.length; index++) {
  96022. light = scene.lights[index];
  96023. var shadowGenerator = light.getShadowGenerator();
  96024. if (shadowGenerator) {
  96025. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96026. }
  96027. }
  96028. // Action Manager
  96029. if (scene.actionManager) {
  96030. serializationObject.actions = scene.actionManager.serialize("scene");
  96031. }
  96032. // Audio
  96033. serializationObject.sounds = [];
  96034. for (index = 0; index < scene.soundTracks.length; index++) {
  96035. var soundtrack = scene.soundTracks[index];
  96036. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96037. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96038. }
  96039. }
  96040. // Effect layers
  96041. serializationObject.effectLayers = [];
  96042. for (index = 0; index < scene.effectLayers.length; index++) {
  96043. var layer = scene.effectLayers[index];
  96044. if (layer.serialize) {
  96045. serializationObject.effectLayers.push(layer.serialize());
  96046. }
  96047. }
  96048. return serializationObject;
  96049. };
  96050. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96051. if (withParents === void 0) { withParents = false; }
  96052. if (withChildren === void 0) { withChildren = false; }
  96053. var serializationObject = {};
  96054. SceneSerializer.ClearCache();
  96055. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96056. if (withParents || withChildren) {
  96057. //deliberate for loop! not for each, appended should be processed as well.
  96058. for (var i = 0; i < toSerialize.length; ++i) {
  96059. if (withChildren) {
  96060. toSerialize[i].getDescendants().forEach(function (node) {
  96061. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96062. toSerialize.push(node);
  96063. }
  96064. });
  96065. }
  96066. //make sure the array doesn't contain the object already
  96067. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96068. toSerialize.push(toSerialize[i].parent);
  96069. }
  96070. }
  96071. }
  96072. toSerialize.forEach(function (mesh) {
  96073. finalizeSingleMesh(mesh, serializationObject);
  96074. });
  96075. return serializationObject;
  96076. };
  96077. return SceneSerializer;
  96078. }());
  96079. BABYLON.SceneSerializer = SceneSerializer;
  96080. })(BABYLON || (BABYLON = {}));
  96081. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96082. var BABYLON;
  96083. (function (BABYLON) {
  96084. var ReflectionProbe = /** @class */ (function () {
  96085. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96086. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96087. var _this = this;
  96088. this.name = name;
  96089. this._viewMatrix = BABYLON.Matrix.Identity();
  96090. this._target = BABYLON.Vector3.Zero();
  96091. this._add = BABYLON.Vector3.Zero();
  96092. this._invertYAxis = false;
  96093. this.position = BABYLON.Vector3.Zero();
  96094. this._scene = scene;
  96095. this._scene.reflectionProbes.push(this);
  96096. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96097. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96098. switch (faceIndex) {
  96099. case 0:
  96100. _this._add.copyFromFloats(1, 0, 0);
  96101. break;
  96102. case 1:
  96103. _this._add.copyFromFloats(-1, 0, 0);
  96104. break;
  96105. case 2:
  96106. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96107. break;
  96108. case 3:
  96109. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96110. break;
  96111. case 4:
  96112. _this._add.copyFromFloats(0, 0, 1);
  96113. break;
  96114. case 5:
  96115. _this._add.copyFromFloats(0, 0, -1);
  96116. break;
  96117. }
  96118. if (_this._attachedMesh) {
  96119. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96120. }
  96121. _this.position.addToRef(_this._add, _this._target);
  96122. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96123. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96124. scene._forcedViewPosition = _this.position;
  96125. });
  96126. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96127. scene._forcedViewPosition = null;
  96128. scene.updateTransformMatrix(true);
  96129. });
  96130. if (scene.activeCamera) {
  96131. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96132. }
  96133. }
  96134. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96135. get: function () {
  96136. return this._renderTargetTexture.samples;
  96137. },
  96138. set: function (value) {
  96139. this._renderTargetTexture.samples = value;
  96140. },
  96141. enumerable: true,
  96142. configurable: true
  96143. });
  96144. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96145. get: function () {
  96146. return this._renderTargetTexture.refreshRate;
  96147. },
  96148. set: function (value) {
  96149. this._renderTargetTexture.refreshRate = value;
  96150. },
  96151. enumerable: true,
  96152. configurable: true
  96153. });
  96154. ReflectionProbe.prototype.getScene = function () {
  96155. return this._scene;
  96156. };
  96157. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96158. get: function () {
  96159. return this._renderTargetTexture;
  96160. },
  96161. enumerable: true,
  96162. configurable: true
  96163. });
  96164. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96165. get: function () {
  96166. return this._renderTargetTexture.renderList;
  96167. },
  96168. enumerable: true,
  96169. configurable: true
  96170. });
  96171. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96172. this._attachedMesh = mesh;
  96173. };
  96174. /**
  96175. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96176. *
  96177. * @param renderingGroupId The rendering group id corresponding to its index
  96178. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96179. */
  96180. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96181. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96182. };
  96183. ReflectionProbe.prototype.dispose = function () {
  96184. var index = this._scene.reflectionProbes.indexOf(this);
  96185. if (index !== -1) {
  96186. // Remove from the scene if found
  96187. this._scene.reflectionProbes.splice(index, 1);
  96188. }
  96189. if (this._renderTargetTexture) {
  96190. this._renderTargetTexture.dispose();
  96191. this._renderTargetTexture = null;
  96192. }
  96193. };
  96194. return ReflectionProbe;
  96195. }());
  96196. BABYLON.ReflectionProbe = ReflectionProbe;
  96197. })(BABYLON || (BABYLON = {}));
  96198. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96199. var BABYLON;
  96200. (function (BABYLON) {
  96201. var Layer = /** @class */ (function () {
  96202. function Layer(name, imgUrl, scene, isBackground, color) {
  96203. this.name = name;
  96204. this.scale = new BABYLON.Vector2(1, 1);
  96205. this.offset = new BABYLON.Vector2(0, 0);
  96206. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96207. this.layerMask = 0x0FFFFFFF;
  96208. this._vertexBuffers = {};
  96209. // Events
  96210. /**
  96211. * An event triggered when the layer is disposed.
  96212. */
  96213. this.onDisposeObservable = new BABYLON.Observable();
  96214. /**
  96215. * An event triggered before rendering the scene
  96216. */
  96217. this.onBeforeRenderObservable = new BABYLON.Observable();
  96218. /**
  96219. * An event triggered after rendering the scene
  96220. */
  96221. this.onAfterRenderObservable = new BABYLON.Observable();
  96222. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96223. this.isBackground = isBackground === undefined ? true : isBackground;
  96224. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96225. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96226. this._scene.layers.push(this);
  96227. var engine = this._scene.getEngine();
  96228. // VBO
  96229. var vertices = [];
  96230. vertices.push(1, 1);
  96231. vertices.push(-1, 1);
  96232. vertices.push(-1, -1);
  96233. vertices.push(1, -1);
  96234. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96235. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96236. this._createIndexBuffer();
  96237. // Effects
  96238. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96239. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96240. }
  96241. Object.defineProperty(Layer.prototype, "onDispose", {
  96242. set: function (callback) {
  96243. if (this._onDisposeObserver) {
  96244. this.onDisposeObservable.remove(this._onDisposeObserver);
  96245. }
  96246. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96247. },
  96248. enumerable: true,
  96249. configurable: true
  96250. });
  96251. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96252. set: function (callback) {
  96253. if (this._onBeforeRenderObserver) {
  96254. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96255. }
  96256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96257. },
  96258. enumerable: true,
  96259. configurable: true
  96260. });
  96261. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96262. set: function (callback) {
  96263. if (this._onAfterRenderObserver) {
  96264. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96265. }
  96266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96267. },
  96268. enumerable: true,
  96269. configurable: true
  96270. });
  96271. Layer.prototype._createIndexBuffer = function () {
  96272. var engine = this._scene.getEngine();
  96273. // Indices
  96274. var indices = [];
  96275. indices.push(0);
  96276. indices.push(1);
  96277. indices.push(2);
  96278. indices.push(0);
  96279. indices.push(2);
  96280. indices.push(3);
  96281. this._indexBuffer = engine.createIndexBuffer(indices);
  96282. };
  96283. Layer.prototype._rebuild = function () {
  96284. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96285. if (vb) {
  96286. vb._rebuild();
  96287. }
  96288. this._createIndexBuffer();
  96289. };
  96290. Layer.prototype.render = function () {
  96291. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96292. // Check
  96293. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96294. return;
  96295. var engine = this._scene.getEngine();
  96296. this.onBeforeRenderObservable.notifyObservers(this);
  96297. // Render
  96298. engine.enableEffect(currentEffect);
  96299. engine.setState(false);
  96300. // Texture
  96301. currentEffect.setTexture("textureSampler", this.texture);
  96302. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96303. // Color
  96304. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96305. // Scale / offset
  96306. currentEffect.setVector2("offset", this.offset);
  96307. currentEffect.setVector2("scale", this.scale);
  96308. // VBOs
  96309. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96310. // Draw order
  96311. if (!this.alphaTest) {
  96312. engine.setAlphaMode(this.alphaBlendingMode);
  96313. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96314. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96315. }
  96316. else {
  96317. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96318. }
  96319. this.onAfterRenderObservable.notifyObservers(this);
  96320. };
  96321. Layer.prototype.dispose = function () {
  96322. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96323. if (vertexBuffer) {
  96324. vertexBuffer.dispose();
  96325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96326. }
  96327. if (this._indexBuffer) {
  96328. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96329. this._indexBuffer = null;
  96330. }
  96331. if (this.texture) {
  96332. this.texture.dispose();
  96333. this.texture = null;
  96334. }
  96335. // Remove from scene
  96336. var index = this._scene.layers.indexOf(this);
  96337. this._scene.layers.splice(index, 1);
  96338. // Callback
  96339. this.onDisposeObservable.notifyObservers(this);
  96340. this.onDisposeObservable.clear();
  96341. this.onAfterRenderObservable.clear();
  96342. this.onBeforeRenderObservable.clear();
  96343. };
  96344. return Layer;
  96345. }());
  96346. BABYLON.Layer = Layer;
  96347. })(BABYLON || (BABYLON = {}));
  96348. //# sourceMappingURL=babylon.layer.js.map
  96349. var BABYLON;
  96350. (function (BABYLON) {
  96351. var TextureTools = /** @class */ (function () {
  96352. function TextureTools() {
  96353. }
  96354. /**
  96355. * Uses the GPU to create a copy texture rescaled at a given size
  96356. * @param texture Texture to copy from
  96357. * @param width Desired width
  96358. * @param height Desired height
  96359. * @return Generated texture
  96360. */
  96361. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96362. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96363. var scene = texture.getScene();
  96364. var engine = scene.getEngine();
  96365. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96366. rtt.wrapU = texture.wrapU;
  96367. rtt.wrapV = texture.wrapV;
  96368. rtt.uOffset = texture.uOffset;
  96369. rtt.vOffset = texture.vOffset;
  96370. rtt.uScale = texture.uScale;
  96371. rtt.vScale = texture.vScale;
  96372. rtt.uAng = texture.uAng;
  96373. rtt.vAng = texture.vAng;
  96374. rtt.wAng = texture.wAng;
  96375. rtt.coordinatesIndex = texture.coordinatesIndex;
  96376. rtt.level = texture.level;
  96377. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96378. rtt._texture.isReady = false;
  96379. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96380. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96381. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96382. passPostProcess.getEffect().executeWhenCompiled(function () {
  96383. passPostProcess.onApply = function (effect) {
  96384. effect.setTexture("textureSampler", texture);
  96385. };
  96386. var internalTexture = rtt.getInternalTexture();
  96387. if (internalTexture) {
  96388. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96389. engine.unBindFramebuffer(internalTexture);
  96390. rtt.disposeFramebufferObjects();
  96391. passPostProcess.dispose();
  96392. internalTexture.isReady = true;
  96393. }
  96394. });
  96395. return rtt;
  96396. };
  96397. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96398. if (!scene._environmentBRDFTexture) {
  96399. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96400. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96401. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96402. scene._environmentBRDFTexture = texture;
  96403. }
  96404. return scene._environmentBRDFTexture;
  96405. };
  96406. 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=";
  96407. return TextureTools;
  96408. }());
  96409. BABYLON.TextureTools = TextureTools;
  96410. })(BABYLON || (BABYLON = {}));
  96411. //# sourceMappingURL=babylon.textureTools.js.map
  96412. var BABYLON;
  96413. (function (BABYLON) {
  96414. var FramingBehavior = /** @class */ (function () {
  96415. function FramingBehavior() {
  96416. this._mode = FramingBehavior.FitFrustumSidesMode;
  96417. this._radiusScale = 1.0;
  96418. this._positionScale = 0.5;
  96419. this._defaultElevation = 0.3;
  96420. this._elevationReturnTime = 1500;
  96421. this._elevationReturnWaitTime = 1000;
  96422. this._zoomStopsAnimation = false;
  96423. this._framingTime = 1500;
  96424. this._isPointerDown = false;
  96425. this._lastInteractionTime = -Infinity;
  96426. // Framing control
  96427. this._animatables = new Array();
  96428. this._betaIsAnimating = false;
  96429. }
  96430. Object.defineProperty(FramingBehavior.prototype, "name", {
  96431. get: function () {
  96432. return "Framing";
  96433. },
  96434. enumerable: true,
  96435. configurable: true
  96436. });
  96437. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96438. /**
  96439. * Gets current mode used by the behavior.
  96440. */
  96441. get: function () {
  96442. return this._mode;
  96443. },
  96444. /**
  96445. * Sets the current mode used by the behavior
  96446. */
  96447. set: function (mode) {
  96448. this._mode = mode;
  96449. },
  96450. enumerable: true,
  96451. configurable: true
  96452. });
  96453. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96454. /**
  96455. * Gets the scale applied to the radius
  96456. */
  96457. get: function () {
  96458. return this._radiusScale;
  96459. },
  96460. /**
  96461. * Sets the scale applied to the radius (1 by default)
  96462. */
  96463. set: function (radius) {
  96464. this._radiusScale = radius;
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96470. /**
  96471. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96472. */
  96473. get: function () {
  96474. return this._positionScale;
  96475. },
  96476. /**
  96477. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96478. */
  96479. set: function (scale) {
  96480. this._positionScale = scale;
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96486. /**
  96487. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96488. * behaviour is triggered, in radians.
  96489. */
  96490. get: function () {
  96491. return this._defaultElevation;
  96492. },
  96493. /**
  96494. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96495. * behaviour is triggered, in radians.
  96496. */
  96497. set: function (elevation) {
  96498. this._defaultElevation = elevation;
  96499. },
  96500. enumerable: true,
  96501. configurable: true
  96502. });
  96503. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96504. /**
  96505. * Gets the time (in milliseconds) taken to return to the default beta position.
  96506. * Negative value indicates camera should not return to default.
  96507. */
  96508. get: function () {
  96509. return this._elevationReturnTime;
  96510. },
  96511. /**
  96512. * Sets the time (in milliseconds) taken to return to the default beta position.
  96513. * Negative value indicates camera should not return to default.
  96514. */
  96515. set: function (speed) {
  96516. this._elevationReturnTime = speed;
  96517. },
  96518. enumerable: true,
  96519. configurable: true
  96520. });
  96521. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96522. /**
  96523. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96524. */
  96525. get: function () {
  96526. return this._elevationReturnWaitTime;
  96527. },
  96528. /**
  96529. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96530. */
  96531. set: function (time) {
  96532. this._elevationReturnWaitTime = time;
  96533. },
  96534. enumerable: true,
  96535. configurable: true
  96536. });
  96537. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96538. /**
  96539. * Gets the flag that indicates if user zooming should stop animation.
  96540. */
  96541. get: function () {
  96542. return this._zoomStopsAnimation;
  96543. },
  96544. /**
  96545. * Sets the flag that indicates if user zooming should stop animation.
  96546. */
  96547. set: function (flag) {
  96548. this._zoomStopsAnimation = flag;
  96549. },
  96550. enumerable: true,
  96551. configurable: true
  96552. });
  96553. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96554. /**
  96555. * Gets the transition time when framing the mesh, in milliseconds
  96556. */
  96557. get: function () {
  96558. return this._framingTime;
  96559. },
  96560. /**
  96561. * Sets the transition time when framing the mesh, in milliseconds
  96562. */
  96563. set: function (time) {
  96564. this._framingTime = time;
  96565. },
  96566. enumerable: true,
  96567. configurable: true
  96568. });
  96569. FramingBehavior.prototype.init = function () {
  96570. // Do notihng
  96571. };
  96572. FramingBehavior.prototype.attach = function (camera) {
  96573. var _this = this;
  96574. this._attachedCamera = camera;
  96575. var scene = this._attachedCamera.getScene();
  96576. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96577. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96578. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96579. _this._isPointerDown = true;
  96580. return;
  96581. }
  96582. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96583. _this._isPointerDown = false;
  96584. }
  96585. });
  96586. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96587. if (mesh) {
  96588. _this.zoomOnMesh(mesh);
  96589. }
  96590. });
  96591. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96592. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96593. _this._applyUserInteraction();
  96594. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96595. // back to the default position after a given timeout
  96596. _this._maintainCameraAboveGround();
  96597. });
  96598. };
  96599. FramingBehavior.prototype.detach = function () {
  96600. if (!this._attachedCamera) {
  96601. return;
  96602. }
  96603. var scene = this._attachedCamera.getScene();
  96604. if (this._onPrePointerObservableObserver) {
  96605. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96606. }
  96607. if (this._onAfterCheckInputsObserver) {
  96608. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96609. }
  96610. if (this._onMeshTargetChangedObserver) {
  96611. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96612. }
  96613. this._attachedCamera = null;
  96614. };
  96615. /**
  96616. * Targets the given mesh and updates zoom level accordingly.
  96617. * @param mesh The mesh to target.
  96618. * @param radius Optional. If a cached radius position already exists, overrides default.
  96619. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96620. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96621. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96622. */
  96623. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96624. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96625. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96626. mesh.computeWorldMatrix(true);
  96627. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96628. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96629. };
  96630. /**
  96631. * Targets the given mesh with its children and updates zoom level accordingly.
  96632. * @param mesh The mesh to target.
  96633. * @param radius Optional. If a cached radius position already exists, overrides default.
  96634. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96635. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96636. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96637. */
  96638. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96639. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96640. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96641. mesh.computeWorldMatrix(true);
  96642. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96643. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96644. };
  96645. /**
  96646. * Targets the given meshes with their children and updates zoom level accordingly.
  96647. * @param meshes The mesh to target.
  96648. * @param radius Optional. If a cached radius position already exists, overrides default.
  96649. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96650. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96651. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96652. */
  96653. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96654. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96655. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96656. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96657. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96658. for (var i = 0; i < meshes.length; i++) {
  96659. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96660. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96661. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96662. }
  96663. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96664. };
  96665. /**
  96666. * Targets the given mesh and updates zoom level accordingly.
  96667. * @param mesh The mesh to target.
  96668. * @param radius Optional. If a cached radius position already exists, overrides default.
  96669. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96670. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96671. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96672. */
  96673. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96674. var _this = this;
  96675. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96676. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96677. var zoomTarget;
  96678. if (!this._attachedCamera) {
  96679. return;
  96680. }
  96681. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96682. var bottom = minimumWorld.y;
  96683. var top = maximumWorld.y;
  96684. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96685. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96686. if (focusOnOriginXZ) {
  96687. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96688. }
  96689. else {
  96690. var centerWorld = minimumWorld.add(radiusWorld);
  96691. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96692. }
  96693. if (!this._vectorTransition) {
  96694. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96695. }
  96696. this._betaIsAnimating = true;
  96697. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96698. if (animatable) {
  96699. this._animatables.push(animatable);
  96700. }
  96701. // sets the radius and lower radius bounds
  96702. // Small delta ensures camera is not always at lower zoom limit.
  96703. var radius = 0;
  96704. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96705. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96706. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96707. radius = position;
  96708. }
  96709. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96710. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96711. if (this._attachedCamera.lowerRadiusLimit === null) {
  96712. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96713. }
  96714. }
  96715. // Set sensibilities
  96716. var extend = maximumWorld.subtract(minimumWorld).length();
  96717. this._attachedCamera.panningSensibility = 5000 / extend;
  96718. this._attachedCamera.wheelPrecision = 100 / radius;
  96719. // transition to new radius
  96720. if (!this._radiusTransition) {
  96721. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96722. }
  96723. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96724. _this.stopAllAnimations();
  96725. if (onAnimationEnd) {
  96726. onAnimationEnd();
  96727. }
  96728. if (_this._attachedCamera) {
  96729. _this._attachedCamera.storeState();
  96730. }
  96731. });
  96732. if (animatable) {
  96733. this._animatables.push(animatable);
  96734. }
  96735. };
  96736. /**
  96737. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96738. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96739. * frustum width.
  96740. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96741. * to fully enclose the mesh in the viewing frustum.
  96742. */
  96743. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96744. var size = maximumWorld.subtract(minimumWorld);
  96745. var boxVectorGlobalDiagonal = size.length();
  96746. var frustumSlope = this._getFrustumSlope();
  96747. // Formula for setting distance
  96748. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96749. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96750. // Horizon distance
  96751. var radius = radiusWithoutFraming * this._radiusScale;
  96752. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96753. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96754. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96755. var camera = this._attachedCamera;
  96756. if (!camera) {
  96757. return 0;
  96758. }
  96759. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96760. // Don't exceed the requested limit
  96761. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96762. }
  96763. // Don't exceed the upper radius limit
  96764. if (camera.upperRadiusLimit) {
  96765. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96766. }
  96767. return distance;
  96768. };
  96769. /**
  96770. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96771. * is automatically returned to its default position (expected to be above ground plane).
  96772. */
  96773. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96774. var _this = this;
  96775. if (this._elevationReturnTime < 0) {
  96776. return;
  96777. }
  96778. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96779. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96780. var limitBeta = Math.PI * 0.5;
  96781. // Bring the camera back up if below the ground plane
  96782. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96783. this._betaIsAnimating = true;
  96784. //Transition to new position
  96785. this.stopAllAnimations();
  96786. if (!this._betaTransition) {
  96787. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96788. }
  96789. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96790. _this._clearAnimationLocks();
  96791. _this.stopAllAnimations();
  96792. });
  96793. if (animatabe) {
  96794. this._animatables.push(animatabe);
  96795. }
  96796. }
  96797. };
  96798. /**
  96799. * Returns the frustum slope based on the canvas ratio and camera FOV
  96800. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96801. */
  96802. FramingBehavior.prototype._getFrustumSlope = function () {
  96803. // Calculate the viewport ratio
  96804. // Aspect Ratio is Height/Width.
  96805. var camera = this._attachedCamera;
  96806. if (!camera) {
  96807. return BABYLON.Vector2.Zero();
  96808. }
  96809. var engine = camera.getScene().getEngine();
  96810. var aspectRatio = engine.getAspectRatio(camera);
  96811. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96812. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96813. var frustumSlopeY = Math.tan(camera.fov / 2);
  96814. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96815. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96816. // along the forward vector.
  96817. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96818. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96819. };
  96820. /**
  96821. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96822. */
  96823. FramingBehavior.prototype._clearAnimationLocks = function () {
  96824. this._betaIsAnimating = false;
  96825. };
  96826. /**
  96827. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96828. */
  96829. FramingBehavior.prototype._applyUserInteraction = function () {
  96830. if (this.isUserIsMoving) {
  96831. this._lastInteractionTime = BABYLON.Tools.Now;
  96832. this.stopAllAnimations();
  96833. this._clearAnimationLocks();
  96834. }
  96835. };
  96836. /**
  96837. * Stops and removes all animations that have been applied to the camera
  96838. */
  96839. FramingBehavior.prototype.stopAllAnimations = function () {
  96840. if (this._attachedCamera) {
  96841. this._attachedCamera.animations = [];
  96842. }
  96843. while (this._animatables.length) {
  96844. if (this._animatables[0]) {
  96845. this._animatables[0].onAnimationEnd = null;
  96846. this._animatables[0].stop();
  96847. }
  96848. this._animatables.shift();
  96849. }
  96850. };
  96851. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96852. /**
  96853. * Gets a value indicating if the user is moving the camera
  96854. */
  96855. get: function () {
  96856. if (!this._attachedCamera) {
  96857. return false;
  96858. }
  96859. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96860. this._attachedCamera.inertialBetaOffset !== 0 ||
  96861. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96862. this._attachedCamera.inertialPanningX !== 0 ||
  96863. this._attachedCamera.inertialPanningY !== 0 ||
  96864. this._isPointerDown;
  96865. },
  96866. enumerable: true,
  96867. configurable: true
  96868. });
  96869. /**
  96870. * The easing function used by animations
  96871. */
  96872. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96873. /**
  96874. * The easing mode used by animations
  96875. */
  96876. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96877. // Statics
  96878. /**
  96879. * The camera can move all the way towards the mesh.
  96880. */
  96881. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96882. /**
  96883. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96884. */
  96885. FramingBehavior.FitFrustumSidesMode = 1;
  96886. return FramingBehavior;
  96887. }());
  96888. BABYLON.FramingBehavior = FramingBehavior;
  96889. })(BABYLON || (BABYLON = {}));
  96890. //# sourceMappingURL=babylon.framingBehavior.js.map
  96891. var BABYLON;
  96892. (function (BABYLON) {
  96893. /**
  96894. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96895. */
  96896. var BouncingBehavior = /** @class */ (function () {
  96897. function BouncingBehavior() {
  96898. /**
  96899. * The duration of the animation, in milliseconds
  96900. */
  96901. this.transitionDuration = 450;
  96902. /**
  96903. * Length of the distance animated by the transition when lower radius is reached
  96904. */
  96905. this.lowerRadiusTransitionRange = 2;
  96906. /**
  96907. * Length of the distance animated by the transition when upper radius is reached
  96908. */
  96909. this.upperRadiusTransitionRange = -2;
  96910. this._autoTransitionRange = false;
  96911. // Animations
  96912. this._radiusIsAnimating = false;
  96913. this._radiusBounceTransition = null;
  96914. this._animatables = new Array();
  96915. }
  96916. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96917. get: function () {
  96918. return "Bouncing";
  96919. },
  96920. enumerable: true,
  96921. configurable: true
  96922. });
  96923. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96924. /**
  96925. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96926. */
  96927. get: function () {
  96928. return this._autoTransitionRange;
  96929. },
  96930. /**
  96931. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96932. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96933. */
  96934. set: function (value) {
  96935. var _this = this;
  96936. if (this._autoTransitionRange === value) {
  96937. return;
  96938. }
  96939. this._autoTransitionRange = value;
  96940. var camera = this._attachedCamera;
  96941. if (!camera) {
  96942. return;
  96943. }
  96944. if (value) {
  96945. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96946. if (!mesh) {
  96947. return;
  96948. }
  96949. mesh.computeWorldMatrix(true);
  96950. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96951. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96952. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96953. });
  96954. }
  96955. else if (this._onMeshTargetChangedObserver) {
  96956. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96957. }
  96958. },
  96959. enumerable: true,
  96960. configurable: true
  96961. });
  96962. BouncingBehavior.prototype.init = function () {
  96963. // Do notihng
  96964. };
  96965. BouncingBehavior.prototype.attach = function (camera) {
  96966. var _this = this;
  96967. this._attachedCamera = camera;
  96968. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96969. if (!_this._attachedCamera) {
  96970. return;
  96971. }
  96972. // Add the bounce animation to the lower radius limit
  96973. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  96974. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  96975. }
  96976. // Add the bounce animation to the upper radius limit
  96977. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  96978. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  96979. }
  96980. });
  96981. };
  96982. BouncingBehavior.prototype.detach = function () {
  96983. if (!this._attachedCamera) {
  96984. return;
  96985. }
  96986. if (this._onAfterCheckInputsObserver) {
  96987. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96988. }
  96989. if (this._onMeshTargetChangedObserver) {
  96990. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96991. }
  96992. this._attachedCamera = null;
  96993. };
  96994. /**
  96995. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  96996. * @param radiusLimit The limit to check against.
  96997. * @return Bool to indicate if at limit.
  96998. */
  96999. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97000. if (!this._attachedCamera) {
  97001. return false;
  97002. }
  97003. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97004. return true;
  97005. }
  97006. return false;
  97007. };
  97008. /**
  97009. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97010. * @param radiusDelta The delta by which to animate to. Can be negative.
  97011. */
  97012. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97013. var _this = this;
  97014. if (!this._attachedCamera) {
  97015. return;
  97016. }
  97017. if (!this._radiusBounceTransition) {
  97018. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97019. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97020. }
  97021. // Prevent zoom until bounce has completed
  97022. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97023. this._attachedCamera.wheelPrecision = Infinity;
  97024. this._attachedCamera.inertialRadiusOffset = 0;
  97025. // Animate to the radius limit
  97026. this.stopAllAnimations();
  97027. this._radiusIsAnimating = true;
  97028. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97029. if (animatable) {
  97030. this._animatables.push(animatable);
  97031. }
  97032. };
  97033. /**
  97034. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97035. */
  97036. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97037. this._radiusIsAnimating = false;
  97038. if (this._attachedCamera) {
  97039. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97040. }
  97041. };
  97042. /**
  97043. * Stops and removes all animations that have been applied to the camera
  97044. */
  97045. BouncingBehavior.prototype.stopAllAnimations = function () {
  97046. if (this._attachedCamera) {
  97047. this._attachedCamera.animations = [];
  97048. }
  97049. while (this._animatables.length) {
  97050. this._animatables[0].onAnimationEnd = null;
  97051. this._animatables[0].stop();
  97052. this._animatables.shift();
  97053. }
  97054. };
  97055. /**
  97056. * The easing function used by animations
  97057. */
  97058. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97059. /**
  97060. * The easing mode used by animations
  97061. */
  97062. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97063. return BouncingBehavior;
  97064. }());
  97065. BABYLON.BouncingBehavior = BouncingBehavior;
  97066. })(BABYLON || (BABYLON = {}));
  97067. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97068. var BABYLON;
  97069. (function (BABYLON) {
  97070. var AutoRotationBehavior = /** @class */ (function () {
  97071. function AutoRotationBehavior() {
  97072. this._zoomStopsAnimation = false;
  97073. this._idleRotationSpeed = 0.05;
  97074. this._idleRotationWaitTime = 2000;
  97075. this._idleRotationSpinupTime = 2000;
  97076. this._isPointerDown = false;
  97077. this._lastFrameTime = null;
  97078. this._lastInteractionTime = -Infinity;
  97079. this._cameraRotationSpeed = 0;
  97080. this._lastFrameRadius = 0;
  97081. }
  97082. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97083. get: function () {
  97084. return "AutoRotation";
  97085. },
  97086. enumerable: true,
  97087. configurable: true
  97088. });
  97089. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97090. /**
  97091. * Gets the flag that indicates if user zooming should stop animation.
  97092. */
  97093. get: function () {
  97094. return this._zoomStopsAnimation;
  97095. },
  97096. /**
  97097. * Sets the flag that indicates if user zooming should stop animation.
  97098. */
  97099. set: function (flag) {
  97100. this._zoomStopsAnimation = flag;
  97101. },
  97102. enumerable: true,
  97103. configurable: true
  97104. });
  97105. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97106. /**
  97107. * Gets the default speed at which the camera rotates around the model.
  97108. */
  97109. get: function () {
  97110. return this._idleRotationSpeed;
  97111. },
  97112. /**
  97113. * Sets the default speed at which the camera rotates around the model.
  97114. */
  97115. set: function (speed) {
  97116. this._idleRotationSpeed = speed;
  97117. },
  97118. enumerable: true,
  97119. configurable: true
  97120. });
  97121. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97122. /**
  97123. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97124. */
  97125. get: function () {
  97126. return this._idleRotationWaitTime;
  97127. },
  97128. /**
  97129. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97130. */
  97131. set: function (time) {
  97132. this._idleRotationWaitTime = time;
  97133. },
  97134. enumerable: true,
  97135. configurable: true
  97136. });
  97137. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97138. /**
  97139. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97140. */
  97141. get: function () {
  97142. return this._idleRotationSpinupTime;
  97143. },
  97144. /**
  97145. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97146. */
  97147. set: function (time) {
  97148. this._idleRotationSpinupTime = time;
  97149. },
  97150. enumerable: true,
  97151. configurable: true
  97152. });
  97153. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97154. /**
  97155. * Gets a value indicating if the camera is currently rotating because of this behavior
  97156. */
  97157. get: function () {
  97158. return Math.abs(this._cameraRotationSpeed) > 0;
  97159. },
  97160. enumerable: true,
  97161. configurable: true
  97162. });
  97163. AutoRotationBehavior.prototype.init = function () {
  97164. // Do notihng
  97165. };
  97166. AutoRotationBehavior.prototype.attach = function (camera) {
  97167. var _this = this;
  97168. this._attachedCamera = camera;
  97169. var scene = this._attachedCamera.getScene();
  97170. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97171. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97172. _this._isPointerDown = true;
  97173. return;
  97174. }
  97175. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97176. _this._isPointerDown = false;
  97177. }
  97178. });
  97179. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97180. var now = BABYLON.Tools.Now;
  97181. var dt = 0;
  97182. if (_this._lastFrameTime != null) {
  97183. dt = now - _this._lastFrameTime;
  97184. }
  97185. _this._lastFrameTime = now;
  97186. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97187. _this._applyUserInteraction();
  97188. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97189. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97190. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97191. // Step camera rotation by rotation speed
  97192. if (_this._attachedCamera) {
  97193. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97194. }
  97195. });
  97196. };
  97197. AutoRotationBehavior.prototype.detach = function () {
  97198. if (!this._attachedCamera) {
  97199. return;
  97200. }
  97201. var scene = this._attachedCamera.getScene();
  97202. if (this._onPrePointerObservableObserver) {
  97203. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97204. }
  97205. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97206. this._attachedCamera = null;
  97207. };
  97208. /**
  97209. * Returns true if user is scrolling.
  97210. * @return true if user is scrolling.
  97211. */
  97212. AutoRotationBehavior.prototype._userIsZooming = function () {
  97213. if (!this._attachedCamera) {
  97214. return false;
  97215. }
  97216. return this._attachedCamera.inertialRadiusOffset !== 0;
  97217. };
  97218. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97219. if (!this._attachedCamera) {
  97220. return false;
  97221. }
  97222. var zoomHasHitLimit = false;
  97223. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97224. zoomHasHitLimit = true;
  97225. }
  97226. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97227. this._lastFrameRadius = this._attachedCamera.radius;
  97228. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97229. };
  97230. /**
  97231. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97232. */
  97233. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97234. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97235. this._lastInteractionTime = BABYLON.Tools.Now;
  97236. }
  97237. };
  97238. // Tools
  97239. AutoRotationBehavior.prototype._userIsMoving = function () {
  97240. if (!this._attachedCamera) {
  97241. return false;
  97242. }
  97243. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97244. this._attachedCamera.inertialBetaOffset !== 0 ||
  97245. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97246. this._attachedCamera.inertialPanningX !== 0 ||
  97247. this._attachedCamera.inertialPanningY !== 0 ||
  97248. this._isPointerDown;
  97249. };
  97250. return AutoRotationBehavior;
  97251. }());
  97252. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97253. })(BABYLON || (BABYLON = {}));
  97254. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97255. var BABYLON;
  97256. (function (BABYLON) {
  97257. var NullEngineOptions = /** @class */ (function () {
  97258. function NullEngineOptions() {
  97259. this.renderWidth = 512;
  97260. this.renderHeight = 256;
  97261. this.textureSize = 512;
  97262. this.deterministicLockstep = false;
  97263. this.lockstepMaxSteps = 4;
  97264. }
  97265. return NullEngineOptions;
  97266. }());
  97267. BABYLON.NullEngineOptions = NullEngineOptions;
  97268. /**
  97269. * The null engine class provides support for headless version of babylon.js.
  97270. * This can be used in server side scenario or for testing purposes
  97271. */
  97272. var NullEngine = /** @class */ (function (_super) {
  97273. __extends(NullEngine, _super);
  97274. function NullEngine(options) {
  97275. if (options === void 0) { options = new NullEngineOptions(); }
  97276. var _this = _super.call(this, null) || this;
  97277. if (options.deterministicLockstep === undefined) {
  97278. options.deterministicLockstep = false;
  97279. }
  97280. if (options.lockstepMaxSteps === undefined) {
  97281. options.lockstepMaxSteps = 4;
  97282. }
  97283. _this._options = options;
  97284. // Init caps
  97285. // We consider we are on a webgl1 capable device
  97286. _this._caps = new BABYLON.EngineCapabilities();
  97287. _this._caps.maxTexturesImageUnits = 16;
  97288. _this._caps.maxVertexTextureImageUnits = 16;
  97289. _this._caps.maxTextureSize = 512;
  97290. _this._caps.maxCubemapTextureSize = 512;
  97291. _this._caps.maxRenderTextureSize = 512;
  97292. _this._caps.maxVertexAttribs = 16;
  97293. _this._caps.maxVaryingVectors = 16;
  97294. _this._caps.maxFragmentUniformVectors = 16;
  97295. _this._caps.maxVertexUniformVectors = 16;
  97296. // Extensions
  97297. _this._caps.standardDerivatives = false;
  97298. _this._caps.astc = null;
  97299. _this._caps.s3tc = null;
  97300. _this._caps.pvrtc = null;
  97301. _this._caps.etc1 = null;
  97302. _this._caps.etc2 = null;
  97303. _this._caps.textureAnisotropicFilterExtension = null;
  97304. _this._caps.maxAnisotropy = 0;
  97305. _this._caps.uintIndices = false;
  97306. _this._caps.fragmentDepthSupported = false;
  97307. _this._caps.highPrecisionShaderSupported = true;
  97308. _this._caps.colorBufferFloat = false;
  97309. _this._caps.textureFloat = false;
  97310. _this._caps.textureFloatLinearFiltering = false;
  97311. _this._caps.textureFloatRender = false;
  97312. _this._caps.textureHalfFloat = false;
  97313. _this._caps.textureHalfFloatLinearFiltering = false;
  97314. _this._caps.textureHalfFloatRender = false;
  97315. _this._caps.textureLOD = false;
  97316. _this._caps.drawBuffersExtension = false;
  97317. _this._caps.depthTextureExtension = false;
  97318. _this._caps.vertexArrayObject = false;
  97319. _this._caps.instancedArrays = false;
  97320. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97321. // Wrappers
  97322. if (typeof URL === "undefined") {
  97323. URL = {
  97324. createObjectURL: function () { },
  97325. revokeObjectURL: function () { }
  97326. };
  97327. }
  97328. if (typeof Blob === "undefined") {
  97329. Blob = function () { };
  97330. }
  97331. return _this;
  97332. }
  97333. NullEngine.prototype.isDeterministicLockStep = function () {
  97334. return this._options.deterministicLockstep;
  97335. };
  97336. NullEngine.prototype.getLockstepMaxSteps = function () {
  97337. return this._options.lockstepMaxSteps;
  97338. };
  97339. NullEngine.prototype.getHardwareScalingLevel = function () {
  97340. return 1.0;
  97341. };
  97342. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97343. return {
  97344. capacity: 0,
  97345. references: 1,
  97346. is32Bits: false
  97347. };
  97348. };
  97349. NullEngine.prototype.createIndexBuffer = function (indices) {
  97350. return {
  97351. capacity: 0,
  97352. references: 1,
  97353. is32Bits: false
  97354. };
  97355. };
  97356. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97357. if (stencil === void 0) { stencil = false; }
  97358. };
  97359. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97360. if (useScreen === void 0) { useScreen = false; }
  97361. if (!useScreen && this._currentRenderTarget) {
  97362. return this._currentRenderTarget.width;
  97363. }
  97364. return this._options.renderWidth;
  97365. };
  97366. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97367. if (useScreen === void 0) { useScreen = false; }
  97368. if (!useScreen && this._currentRenderTarget) {
  97369. return this._currentRenderTarget.height;
  97370. }
  97371. return this._options.renderHeight;
  97372. };
  97373. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97374. this._cachedViewport = viewport;
  97375. };
  97376. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97377. return {
  97378. transformFeedback: null,
  97379. __SPECTOR_rebuildProgram: null
  97380. };
  97381. };
  97382. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97383. return [];
  97384. };
  97385. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97386. return [];
  97387. };
  97388. NullEngine.prototype.bindSamplers = function (effect) {
  97389. this._currentEffect = null;
  97390. };
  97391. NullEngine.prototype.enableEffect = function (effect) {
  97392. this._currentEffect = effect;
  97393. if (effect.onBind) {
  97394. effect.onBind(effect);
  97395. }
  97396. effect.onBindObservable.notifyObservers(effect);
  97397. };
  97398. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97399. if (zOffset === void 0) { zOffset = 0; }
  97400. if (reverseSide === void 0) { reverseSide = false; }
  97401. };
  97402. NullEngine.prototype.setIntArray = function (uniform, array) {
  97403. };
  97404. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97405. };
  97406. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97407. };
  97408. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97409. };
  97410. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97411. };
  97412. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97413. };
  97414. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97415. };
  97416. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97417. };
  97418. NullEngine.prototype.setArray = function (uniform, array) {
  97419. };
  97420. NullEngine.prototype.setArray2 = function (uniform, array) {
  97421. };
  97422. NullEngine.prototype.setArray3 = function (uniform, array) {
  97423. };
  97424. NullEngine.prototype.setArray4 = function (uniform, array) {
  97425. };
  97426. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97427. };
  97428. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97429. };
  97430. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97431. };
  97432. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97433. };
  97434. NullEngine.prototype.setFloat = function (uniform, value) {
  97435. };
  97436. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97437. };
  97438. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97439. };
  97440. NullEngine.prototype.setBool = function (uniform, bool) {
  97441. };
  97442. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97443. };
  97444. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97445. };
  97446. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97447. };
  97448. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97450. if (this._alphaMode === mode) {
  97451. return;
  97452. }
  97453. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97454. if (!noDepthWriteChange) {
  97455. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97456. }
  97457. this._alphaMode = mode;
  97458. };
  97459. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97460. };
  97461. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97462. if (this.preventCacheWipeBetweenFrames) {
  97463. return;
  97464. }
  97465. this.resetTextureCache();
  97466. this._currentEffect = null;
  97467. if (bruteForce) {
  97468. this._currentProgram = null;
  97469. this._stencilState.reset();
  97470. this._depthCullingState.reset();
  97471. this._alphaState.reset();
  97472. }
  97473. this._cachedVertexBuffers = null;
  97474. this._cachedIndexBuffer = null;
  97475. this._cachedEffectForVertexBuffers = null;
  97476. };
  97477. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97478. };
  97479. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97480. };
  97481. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97482. };
  97483. NullEngine.prototype._createTexture = function () {
  97484. return {};
  97485. };
  97486. NullEngine.prototype._releaseTexture = function (texture) {
  97487. };
  97488. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97490. if (onLoad === void 0) { onLoad = null; }
  97491. if (onError === void 0) { onError = null; }
  97492. if (buffer === void 0) { buffer = null; }
  97493. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97494. var url = String(urlArg);
  97495. texture.url = url;
  97496. texture.generateMipMaps = !noMipmap;
  97497. texture.samplingMode = samplingMode;
  97498. texture.invertY = invertY;
  97499. texture.baseWidth = this._options.textureSize;
  97500. texture.baseHeight = this._options.textureSize;
  97501. texture.width = this._options.textureSize;
  97502. texture.height = this._options.textureSize;
  97503. if (format) {
  97504. texture.format = format;
  97505. }
  97506. texture.isReady = true;
  97507. if (onLoad) {
  97508. onLoad();
  97509. }
  97510. this._internalTexturesCache.push(texture);
  97511. return texture;
  97512. };
  97513. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97514. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97515. if (options !== undefined && typeof options === "object") {
  97516. fullOptions.generateMipMaps = options.generateMipMaps;
  97517. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97518. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97519. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97520. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97521. }
  97522. else {
  97523. fullOptions.generateMipMaps = options;
  97524. fullOptions.generateDepthBuffer = true;
  97525. fullOptions.generateStencilBuffer = false;
  97526. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97527. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97528. }
  97529. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97530. var width = size.width || size;
  97531. var height = size.height || size;
  97532. texture._depthStencilBuffer = {};
  97533. texture._framebuffer = {};
  97534. texture.baseWidth = width;
  97535. texture.baseHeight = height;
  97536. texture.width = width;
  97537. texture.height = height;
  97538. texture.isReady = true;
  97539. texture.samples = 1;
  97540. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97541. texture.samplingMode = fullOptions.samplingMode;
  97542. texture.type = fullOptions.type;
  97543. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97544. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97545. this._internalTexturesCache.push(texture);
  97546. return texture;
  97547. };
  97548. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97549. texture.samplingMode = samplingMode;
  97550. };
  97551. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97552. if (this._currentRenderTarget) {
  97553. this.unBindFramebuffer(this._currentRenderTarget);
  97554. }
  97555. this._currentRenderTarget = texture;
  97556. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97557. if (this._cachedViewport && !forceFullscreenViewport) {
  97558. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97559. }
  97560. };
  97561. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97562. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97563. this._currentRenderTarget = null;
  97564. if (onBeforeUnbind) {
  97565. if (texture._MSAAFramebuffer) {
  97566. this._currentFramebuffer = texture._framebuffer;
  97567. }
  97568. onBeforeUnbind();
  97569. }
  97570. this._currentFramebuffer = null;
  97571. };
  97572. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97573. var vbo = {
  97574. capacity: 1,
  97575. references: 1,
  97576. is32Bits: false
  97577. };
  97578. return vbo;
  97579. };
  97580. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97581. if (offset === void 0) { offset = 0; }
  97582. };
  97583. /**
  97584. * Updates a dynamic vertex buffer.
  97585. * @param vertexBuffer the vertex buffer to update
  97586. * @param data the data used to update the vertex buffer
  97587. * @param byteOffset the byte offset of the data (optional)
  97588. * @param byteLength the byte length of the data (optional)
  97589. */
  97590. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97591. };
  97592. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97593. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97594. this._boundTexturesCache[this._activeChannel] = texture;
  97595. }
  97596. };
  97597. NullEngine.prototype._bindTexture = function (channel, texture) {
  97598. if (channel < 0) {
  97599. return;
  97600. }
  97601. this._bindTextureDirectly(0, texture);
  97602. };
  97603. NullEngine.prototype._releaseBuffer = function (buffer) {
  97604. buffer.references--;
  97605. if (buffer.references === 0) {
  97606. return true;
  97607. }
  97608. return false;
  97609. };
  97610. NullEngine.prototype.releaseEffects = function () {
  97611. };
  97612. return NullEngine;
  97613. }(BABYLON.Engine));
  97614. BABYLON.NullEngine = NullEngine;
  97615. })(BABYLON || (BABYLON = {}));
  97616. //# sourceMappingURL=babylon.nullEngine.js.map
  97617. var BABYLON;
  97618. (function (BABYLON) {
  97619. /**
  97620. * This class can be used to get instrumentation data from a Babylon engine
  97621. */
  97622. var EngineInstrumentation = /** @class */ (function () {
  97623. function EngineInstrumentation(engine) {
  97624. this.engine = engine;
  97625. this._captureGPUFrameTime = false;
  97626. this._gpuFrameTime = new BABYLON.PerfCounter();
  97627. this._captureShaderCompilationTime = false;
  97628. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97629. // Observers
  97630. this._onBeginFrameObserver = null;
  97631. this._onEndFrameObserver = null;
  97632. this._onBeforeShaderCompilationObserver = null;
  97633. this._onAfterShaderCompilationObserver = null;
  97634. }
  97635. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97636. // Properties
  97637. /**
  97638. * Gets the perf counter used for GPU frame time
  97639. */
  97640. get: function () {
  97641. return this._gpuFrameTime;
  97642. },
  97643. enumerable: true,
  97644. configurable: true
  97645. });
  97646. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97647. /**
  97648. * Gets the GPU frame time capture status
  97649. */
  97650. get: function () {
  97651. return this._captureGPUFrameTime;
  97652. },
  97653. /**
  97654. * Enable or disable the GPU frame time capture
  97655. */
  97656. set: function (value) {
  97657. var _this = this;
  97658. if (value === this._captureGPUFrameTime) {
  97659. return;
  97660. }
  97661. this._captureGPUFrameTime = value;
  97662. if (value) {
  97663. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97664. if (!_this._gpuFrameTimeToken) {
  97665. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97666. }
  97667. });
  97668. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97669. if (!_this._gpuFrameTimeToken) {
  97670. return;
  97671. }
  97672. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97673. if (time > -1) {
  97674. _this._gpuFrameTimeToken = null;
  97675. _this._gpuFrameTime.fetchNewFrame();
  97676. _this._gpuFrameTime.addCount(time, true);
  97677. }
  97678. });
  97679. }
  97680. else {
  97681. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97682. this._onBeginFrameObserver = null;
  97683. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97684. this._onEndFrameObserver = null;
  97685. }
  97686. },
  97687. enumerable: true,
  97688. configurable: true
  97689. });
  97690. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97691. /**
  97692. * Gets the perf counter used for shader compilation time
  97693. */
  97694. get: function () {
  97695. return this._shaderCompilationTime;
  97696. },
  97697. enumerable: true,
  97698. configurable: true
  97699. });
  97700. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97701. /**
  97702. * Gets the shader compilation time capture status
  97703. */
  97704. get: function () {
  97705. return this._captureShaderCompilationTime;
  97706. },
  97707. /**
  97708. * Enable or disable the shader compilation time capture
  97709. */
  97710. set: function (value) {
  97711. var _this = this;
  97712. if (value === this._captureShaderCompilationTime) {
  97713. return;
  97714. }
  97715. this._captureShaderCompilationTime = value;
  97716. if (value) {
  97717. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97718. _this._shaderCompilationTime.fetchNewFrame();
  97719. _this._shaderCompilationTime.beginMonitoring();
  97720. });
  97721. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97722. _this._shaderCompilationTime.endMonitoring();
  97723. });
  97724. }
  97725. else {
  97726. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97727. this._onBeforeShaderCompilationObserver = null;
  97728. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97729. this._onAfterShaderCompilationObserver = null;
  97730. }
  97731. },
  97732. enumerable: true,
  97733. configurable: true
  97734. });
  97735. EngineInstrumentation.prototype.dispose = function () {
  97736. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97737. this._onBeginFrameObserver = null;
  97738. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97739. this._onEndFrameObserver = null;
  97740. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97741. this._onBeforeShaderCompilationObserver = null;
  97742. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97743. this._onAfterShaderCompilationObserver = null;
  97744. this.engine = null;
  97745. };
  97746. return EngineInstrumentation;
  97747. }());
  97748. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97749. })(BABYLON || (BABYLON = {}));
  97750. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97751. var BABYLON;
  97752. (function (BABYLON) {
  97753. /**
  97754. * This class can be used to get instrumentation data from a Babylon engine
  97755. */
  97756. var SceneInstrumentation = /** @class */ (function () {
  97757. function SceneInstrumentation(scene) {
  97758. var _this = this;
  97759. this.scene = scene;
  97760. this._captureActiveMeshesEvaluationTime = false;
  97761. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97762. this._captureRenderTargetsRenderTime = false;
  97763. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97764. this._captureFrameTime = false;
  97765. this._frameTime = new BABYLON.PerfCounter();
  97766. this._captureRenderTime = false;
  97767. this._renderTime = new BABYLON.PerfCounter();
  97768. this._captureInterFrameTime = false;
  97769. this._interFrameTime = new BABYLON.PerfCounter();
  97770. this._captureParticlesRenderTime = false;
  97771. this._particlesRenderTime = new BABYLON.PerfCounter();
  97772. this._captureSpritesRenderTime = false;
  97773. this._spritesRenderTime = new BABYLON.PerfCounter();
  97774. this._capturePhysicsTime = false;
  97775. this._physicsTime = new BABYLON.PerfCounter();
  97776. this._captureAnimationsTime = false;
  97777. this._animationsTime = new BABYLON.PerfCounter();
  97778. // Observers
  97779. this._onBeforeActiveMeshesEvaluationObserver = null;
  97780. this._onAfterActiveMeshesEvaluationObserver = null;
  97781. this._onBeforeRenderTargetsRenderObserver = null;
  97782. this._onAfterRenderTargetsRenderObserver = null;
  97783. this._onAfterRenderObserver = null;
  97784. this._onBeforeDrawPhaseObserver = null;
  97785. this._onAfterDrawPhaseObserver = null;
  97786. this._onBeforeAnimationsObserver = null;
  97787. this._onBeforeParticlesRenderingObserver = null;
  97788. this._onAfterParticlesRenderingObserver = null;
  97789. this._onBeforeSpritesRenderingObserver = null;
  97790. this._onAfterSpritesRenderingObserver = null;
  97791. this._onBeforePhysicsObserver = null;
  97792. this._onAfterPhysicsObserver = null;
  97793. this._onAfterAnimationsObserver = null;
  97794. // Before render
  97795. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97796. if (_this._captureActiveMeshesEvaluationTime) {
  97797. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97798. }
  97799. if (_this._captureRenderTargetsRenderTime) {
  97800. _this._renderTargetsRenderTime.fetchNewFrame();
  97801. }
  97802. if (_this._captureFrameTime) {
  97803. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97804. _this._frameTime.beginMonitoring();
  97805. }
  97806. if (_this._captureInterFrameTime) {
  97807. _this._interFrameTime.endMonitoring();
  97808. }
  97809. if (_this._captureParticlesRenderTime) {
  97810. _this._particlesRenderTime.fetchNewFrame();
  97811. }
  97812. if (_this._captureSpritesRenderTime) {
  97813. _this._spritesRenderTime.fetchNewFrame();
  97814. }
  97815. if (_this._captureAnimationsTime) {
  97816. _this._animationsTime.beginMonitoring();
  97817. }
  97818. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97819. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97820. });
  97821. // After render
  97822. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97823. if (_this._captureFrameTime) {
  97824. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97825. _this._frameTime.endMonitoring();
  97826. }
  97827. if (_this._captureRenderTime) {
  97828. _this._renderTime.endMonitoring(false);
  97829. }
  97830. if (_this._captureInterFrameTime) {
  97831. _this._interFrameTime.beginMonitoring();
  97832. }
  97833. });
  97834. }
  97835. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97836. // Properties
  97837. /**
  97838. * Gets the perf counter used for active meshes evaluation time
  97839. */
  97840. get: function () {
  97841. return this._activeMeshesEvaluationTime;
  97842. },
  97843. enumerable: true,
  97844. configurable: true
  97845. });
  97846. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97847. /**
  97848. * Gets the active meshes evaluation time capture status
  97849. */
  97850. get: function () {
  97851. return this._captureActiveMeshesEvaluationTime;
  97852. },
  97853. /**
  97854. * Enable or disable the active meshes evaluation time capture
  97855. */
  97856. set: function (value) {
  97857. var _this = this;
  97858. if (value === this._captureActiveMeshesEvaluationTime) {
  97859. return;
  97860. }
  97861. this._captureActiveMeshesEvaluationTime = value;
  97862. if (value) {
  97863. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97864. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97865. _this._activeMeshesEvaluationTime.beginMonitoring();
  97866. });
  97867. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97868. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97869. _this._activeMeshesEvaluationTime.endMonitoring();
  97870. });
  97871. }
  97872. else {
  97873. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97874. this._onBeforeActiveMeshesEvaluationObserver = null;
  97875. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97876. this._onAfterActiveMeshesEvaluationObserver = null;
  97877. }
  97878. },
  97879. enumerable: true,
  97880. configurable: true
  97881. });
  97882. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97883. /**
  97884. * Gets the perf counter used for render targets render time
  97885. */
  97886. get: function () {
  97887. return this._renderTargetsRenderTime;
  97888. },
  97889. enumerable: true,
  97890. configurable: true
  97891. });
  97892. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97893. /**
  97894. * Gets the render targets render time capture status
  97895. */
  97896. get: function () {
  97897. return this._captureRenderTargetsRenderTime;
  97898. },
  97899. /**
  97900. * Enable or disable the render targets render time capture
  97901. */
  97902. set: function (value) {
  97903. var _this = this;
  97904. if (value === this._captureRenderTargetsRenderTime) {
  97905. return;
  97906. }
  97907. this._captureRenderTargetsRenderTime = value;
  97908. if (value) {
  97909. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97910. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97911. _this._renderTargetsRenderTime.beginMonitoring();
  97912. });
  97913. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97914. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97915. _this._renderTargetsRenderTime.endMonitoring(false);
  97916. });
  97917. }
  97918. else {
  97919. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97920. this._onBeforeRenderTargetsRenderObserver = null;
  97921. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97922. this._onAfterRenderTargetsRenderObserver = null;
  97923. }
  97924. },
  97925. enumerable: true,
  97926. configurable: true
  97927. });
  97928. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97929. /**
  97930. * Gets the perf counter used for particles render time
  97931. */
  97932. get: function () {
  97933. return this._particlesRenderTime;
  97934. },
  97935. enumerable: true,
  97936. configurable: true
  97937. });
  97938. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97939. /**
  97940. * Gets the particles render time capture status
  97941. */
  97942. get: function () {
  97943. return this._captureParticlesRenderTime;
  97944. },
  97945. /**
  97946. * Enable or disable the particles render time capture
  97947. */
  97948. set: function (value) {
  97949. var _this = this;
  97950. if (value === this._captureParticlesRenderTime) {
  97951. return;
  97952. }
  97953. this._captureParticlesRenderTime = value;
  97954. if (value) {
  97955. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97956. BABYLON.Tools.StartPerformanceCounter("Particles");
  97957. _this._particlesRenderTime.beginMonitoring();
  97958. });
  97959. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97960. BABYLON.Tools.EndPerformanceCounter("Particles");
  97961. _this._particlesRenderTime.endMonitoring(false);
  97962. });
  97963. }
  97964. else {
  97965. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97966. this._onBeforeParticlesRenderingObserver = null;
  97967. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97968. this._onAfterParticlesRenderingObserver = null;
  97969. }
  97970. },
  97971. enumerable: true,
  97972. configurable: true
  97973. });
  97974. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97975. /**
  97976. * Gets the perf counter used for sprites render time
  97977. */
  97978. get: function () {
  97979. return this._spritesRenderTime;
  97980. },
  97981. enumerable: true,
  97982. configurable: true
  97983. });
  97984. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97985. /**
  97986. * Gets the sprites render time capture status
  97987. */
  97988. get: function () {
  97989. return this._captureSpritesRenderTime;
  97990. },
  97991. /**
  97992. * Enable or disable the sprites render time capture
  97993. */
  97994. set: function (value) {
  97995. var _this = this;
  97996. if (value === this._captureSpritesRenderTime) {
  97997. return;
  97998. }
  97999. this._captureSpritesRenderTime = value;
  98000. if (value) {
  98001. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98002. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98003. _this._spritesRenderTime.beginMonitoring();
  98004. });
  98005. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98006. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98007. _this._spritesRenderTime.endMonitoring(false);
  98008. });
  98009. }
  98010. else {
  98011. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98012. this._onBeforeSpritesRenderingObserver = null;
  98013. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98014. this._onAfterSpritesRenderingObserver = null;
  98015. }
  98016. },
  98017. enumerable: true,
  98018. configurable: true
  98019. });
  98020. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98021. /**
  98022. * Gets the perf counter used for physics time
  98023. */
  98024. get: function () {
  98025. return this._physicsTime;
  98026. },
  98027. enumerable: true,
  98028. configurable: true
  98029. });
  98030. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98031. /**
  98032. * Gets the physics time capture status
  98033. */
  98034. get: function () {
  98035. return this._capturePhysicsTime;
  98036. },
  98037. /**
  98038. * Enable or disable the physics time capture
  98039. */
  98040. set: function (value) {
  98041. var _this = this;
  98042. if (value === this._capturePhysicsTime) {
  98043. return;
  98044. }
  98045. this._capturePhysicsTime = value;
  98046. if (value) {
  98047. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98048. BABYLON.Tools.StartPerformanceCounter("Physics");
  98049. _this._physicsTime.beginMonitoring();
  98050. });
  98051. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98052. BABYLON.Tools.EndPerformanceCounter("Physics");
  98053. _this._physicsTime.endMonitoring();
  98054. });
  98055. }
  98056. else {
  98057. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98058. this._onBeforePhysicsObserver = null;
  98059. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98060. this._onAfterPhysicsObserver = null;
  98061. }
  98062. },
  98063. enumerable: true,
  98064. configurable: true
  98065. });
  98066. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98067. /**
  98068. * Gets the perf counter used for animations time
  98069. */
  98070. get: function () {
  98071. return this._animationsTime;
  98072. },
  98073. enumerable: true,
  98074. configurable: true
  98075. });
  98076. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98077. /**
  98078. * Gets the animations time capture status
  98079. */
  98080. get: function () {
  98081. return this._captureAnimationsTime;
  98082. },
  98083. /**
  98084. * Enable or disable the animations time capture
  98085. */
  98086. set: function (value) {
  98087. var _this = this;
  98088. if (value === this._captureAnimationsTime) {
  98089. return;
  98090. }
  98091. this._captureAnimationsTime = value;
  98092. if (value) {
  98093. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98094. _this._animationsTime.endMonitoring();
  98095. });
  98096. }
  98097. else {
  98098. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98099. this._onAfterAnimationsObserver = null;
  98100. }
  98101. },
  98102. enumerable: true,
  98103. configurable: true
  98104. });
  98105. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98106. /**
  98107. * Gets the perf counter used for frame time capture
  98108. */
  98109. get: function () {
  98110. return this._frameTime;
  98111. },
  98112. enumerable: true,
  98113. configurable: true
  98114. });
  98115. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98116. /**
  98117. * Gets the frame time capture status
  98118. */
  98119. get: function () {
  98120. return this._captureFrameTime;
  98121. },
  98122. /**
  98123. * Enable or disable the frame time capture
  98124. */
  98125. set: function (value) {
  98126. this._captureFrameTime = value;
  98127. },
  98128. enumerable: true,
  98129. configurable: true
  98130. });
  98131. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98132. /**
  98133. * Gets the perf counter used for inter-frames time capture
  98134. */
  98135. get: function () {
  98136. return this._interFrameTime;
  98137. },
  98138. enumerable: true,
  98139. configurable: true
  98140. });
  98141. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98142. /**
  98143. * Gets the inter-frames time capture status
  98144. */
  98145. get: function () {
  98146. return this._captureInterFrameTime;
  98147. },
  98148. /**
  98149. * Enable or disable the inter-frames time capture
  98150. */
  98151. set: function (value) {
  98152. this._captureInterFrameTime = value;
  98153. },
  98154. enumerable: true,
  98155. configurable: true
  98156. });
  98157. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98158. /**
  98159. * Gets the perf counter used for render time capture
  98160. */
  98161. get: function () {
  98162. return this._renderTime;
  98163. },
  98164. enumerable: true,
  98165. configurable: true
  98166. });
  98167. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98168. /**
  98169. * Gets the render time capture status
  98170. */
  98171. get: function () {
  98172. return this._captureRenderTime;
  98173. },
  98174. /**
  98175. * Enable or disable the render time capture
  98176. */
  98177. set: function (value) {
  98178. var _this = this;
  98179. if (value === this._captureRenderTime) {
  98180. return;
  98181. }
  98182. this._captureRenderTime = value;
  98183. if (value) {
  98184. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98185. _this._renderTime.beginMonitoring();
  98186. BABYLON.Tools.StartPerformanceCounter("Main render");
  98187. });
  98188. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98189. _this._renderTime.endMonitoring(false);
  98190. BABYLON.Tools.EndPerformanceCounter("Main render");
  98191. });
  98192. }
  98193. else {
  98194. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98195. this._onBeforeDrawPhaseObserver = null;
  98196. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98197. this._onAfterDrawPhaseObserver = null;
  98198. }
  98199. },
  98200. enumerable: true,
  98201. configurable: true
  98202. });
  98203. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98204. /**
  98205. * Gets the perf counter used for draw calls
  98206. */
  98207. get: function () {
  98208. return this.scene.getEngine()._drawCalls;
  98209. },
  98210. enumerable: true,
  98211. configurable: true
  98212. });
  98213. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98214. /**
  98215. * Gets the perf counter used for texture collisions
  98216. */
  98217. get: function () {
  98218. return this.scene.getEngine()._textureCollisions;
  98219. },
  98220. enumerable: true,
  98221. configurable: true
  98222. });
  98223. SceneInstrumentation.prototype.dispose = function () {
  98224. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98225. this._onAfterRenderObserver = null;
  98226. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98227. this._onBeforeActiveMeshesEvaluationObserver = null;
  98228. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98229. this._onAfterActiveMeshesEvaluationObserver = null;
  98230. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98231. this._onBeforeRenderTargetsRenderObserver = null;
  98232. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98233. this._onAfterRenderTargetsRenderObserver = null;
  98234. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98235. this._onBeforeAnimationsObserver = null;
  98236. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98237. this._onBeforeParticlesRenderingObserver = null;
  98238. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98239. this._onAfterParticlesRenderingObserver = null;
  98240. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98241. this._onBeforeSpritesRenderingObserver = null;
  98242. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98243. this._onAfterSpritesRenderingObserver = null;
  98244. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98245. this._onBeforeDrawPhaseObserver = null;
  98246. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98247. this._onAfterDrawPhaseObserver = null;
  98248. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98249. this._onBeforePhysicsObserver = null;
  98250. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98251. this._onAfterPhysicsObserver = null;
  98252. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98253. this._onAfterAnimationsObserver = null;
  98254. this.scene = null;
  98255. };
  98256. return SceneInstrumentation;
  98257. }());
  98258. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98259. })(BABYLON || (BABYLON = {}));
  98260. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98261. var BABYLON;
  98262. (function (BABYLON) {
  98263. /**
  98264. * @hidden
  98265. **/
  98266. var _TimeToken = /** @class */ (function () {
  98267. function _TimeToken() {
  98268. this._timeElapsedQueryEnded = false;
  98269. }
  98270. return _TimeToken;
  98271. }());
  98272. BABYLON._TimeToken = _TimeToken;
  98273. })(BABYLON || (BABYLON = {}));
  98274. //# sourceMappingURL=babylon.timeToken.js.map
  98275. var BABYLON;
  98276. (function (BABYLON) {
  98277. /**
  98278. * Background material defines definition.
  98279. * @hidden Mainly internal Use
  98280. */
  98281. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98282. __extends(BackgroundMaterialDefines, _super);
  98283. /**
  98284. * Constructor of the defines.
  98285. */
  98286. function BackgroundMaterialDefines() {
  98287. var _this = _super.call(this) || this;
  98288. /**
  98289. * True if the diffuse texture is in use.
  98290. */
  98291. _this.DIFFUSE = false;
  98292. /**
  98293. * The direct UV channel to use.
  98294. */
  98295. _this.DIFFUSEDIRECTUV = 0;
  98296. /**
  98297. * True if the diffuse texture is in gamma space.
  98298. */
  98299. _this.GAMMADIFFUSE = false;
  98300. /**
  98301. * True if the diffuse texture has opacity in the alpha channel.
  98302. */
  98303. _this.DIFFUSEHASALPHA = false;
  98304. /**
  98305. * True if you want the material to fade to transparent at grazing angle.
  98306. */
  98307. _this.OPACITYFRESNEL = false;
  98308. /**
  98309. * True if an extra blur needs to be added in the reflection.
  98310. */
  98311. _this.REFLECTIONBLUR = false;
  98312. /**
  98313. * True if you want the material to fade to reflection at grazing angle.
  98314. */
  98315. _this.REFLECTIONFRESNEL = false;
  98316. /**
  98317. * True if you want the material to falloff as far as you move away from the scene center.
  98318. */
  98319. _this.REFLECTIONFALLOFF = false;
  98320. /**
  98321. * False if the current Webgl implementation does not support the texture lod extension.
  98322. */
  98323. _this.TEXTURELODSUPPORT = false;
  98324. /**
  98325. * True to ensure the data are premultiplied.
  98326. */
  98327. _this.PREMULTIPLYALPHA = false;
  98328. /**
  98329. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98330. */
  98331. _this.USERGBCOLOR = false;
  98332. /**
  98333. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98334. * stays aligned with the desired configuration.
  98335. */
  98336. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98337. /**
  98338. * True to add noise in order to reduce the banding effect.
  98339. */
  98340. _this.NOISE = false;
  98341. /**
  98342. * is the reflection texture in BGR color scheme?
  98343. * Mainly used to solve a bug in ios10 video tag
  98344. */
  98345. _this.REFLECTIONBGR = false;
  98346. _this.IMAGEPROCESSING = false;
  98347. _this.VIGNETTE = false;
  98348. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98349. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98350. _this.TONEMAPPING = false;
  98351. _this.CONTRAST = false;
  98352. _this.COLORCURVES = false;
  98353. _this.COLORGRADING = false;
  98354. _this.COLORGRADING3D = false;
  98355. _this.SAMPLER3DGREENDEPTH = false;
  98356. _this.SAMPLER3DBGRMAP = false;
  98357. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98358. _this.EXPOSURE = false;
  98359. // Reflection.
  98360. _this.REFLECTION = false;
  98361. _this.REFLECTIONMAP_3D = false;
  98362. _this.REFLECTIONMAP_SPHERICAL = false;
  98363. _this.REFLECTIONMAP_PLANAR = false;
  98364. _this.REFLECTIONMAP_CUBIC = false;
  98365. _this.REFLECTIONMAP_PROJECTION = false;
  98366. _this.REFLECTIONMAP_SKYBOX = false;
  98367. _this.REFLECTIONMAP_EXPLICIT = false;
  98368. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98369. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98370. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98371. _this.INVERTCUBICMAP = false;
  98372. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98373. _this.LODINREFLECTIONALPHA = false;
  98374. _this.GAMMAREFLECTION = false;
  98375. _this.RGBDREFLECTION = false;
  98376. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98377. // Default BJS.
  98378. _this.MAINUV1 = false;
  98379. _this.MAINUV2 = false;
  98380. _this.UV1 = false;
  98381. _this.UV2 = false;
  98382. _this.CLIPPLANE = false;
  98383. _this.POINTSIZE = false;
  98384. _this.FOG = false;
  98385. _this.NORMAL = false;
  98386. _this.NUM_BONE_INFLUENCERS = 0;
  98387. _this.BonesPerMesh = 0;
  98388. _this.INSTANCES = false;
  98389. _this.SHADOWFLOAT = false;
  98390. _this.rebuild();
  98391. return _this;
  98392. }
  98393. return BackgroundMaterialDefines;
  98394. }(BABYLON.MaterialDefines));
  98395. /**
  98396. * Background material used to create an efficient environement around your scene.
  98397. */
  98398. var BackgroundMaterial = /** @class */ (function (_super) {
  98399. __extends(BackgroundMaterial, _super);
  98400. /**
  98401. * Instantiates a Background Material in the given scene
  98402. * @param name The friendly name of the material
  98403. * @param scene The scene to add the material to
  98404. */
  98405. function BackgroundMaterial(name, scene) {
  98406. var _this = _super.call(this, name, scene) || this;
  98407. /**
  98408. * Key light Color (multiply against the environement texture)
  98409. */
  98410. _this.primaryColor = BABYLON.Color3.White();
  98411. _this._primaryColorShadowLevel = 0;
  98412. _this._primaryColorHighlightLevel = 0;
  98413. /**
  98414. * Reflection Texture used in the material.
  98415. * Should be author in a specific way for the best result (refer to the documentation).
  98416. */
  98417. _this.reflectionTexture = null;
  98418. /**
  98419. * Reflection Texture level of blur.
  98420. *
  98421. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98422. * texture twice.
  98423. */
  98424. _this.reflectionBlur = 0;
  98425. /**
  98426. * Diffuse Texture used in the material.
  98427. * Should be author in a specific way for the best result (refer to the documentation).
  98428. */
  98429. _this.diffuseTexture = null;
  98430. _this._shadowLights = null;
  98431. /**
  98432. * Specify the list of lights casting shadow on the material.
  98433. * All scene shadow lights will be included if null.
  98434. */
  98435. _this.shadowLights = null;
  98436. /**
  98437. * Helps adjusting the shadow to a softer level if required.
  98438. * 0 means black shadows and 1 means no shadows.
  98439. */
  98440. _this.shadowLevel = 0;
  98441. /**
  98442. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98443. * It is usually zero but might be interesting to modify according to your setup.
  98444. */
  98445. _this.sceneCenter = BABYLON.Vector3.Zero();
  98446. /**
  98447. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98448. * This helps ensuring a nice transition when the camera goes under the ground.
  98449. */
  98450. _this.opacityFresnel = true;
  98451. /**
  98452. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98453. * This helps adding a mirror texture on the ground.
  98454. */
  98455. _this.reflectionFresnel = false;
  98456. /**
  98457. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98458. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98459. */
  98460. _this.reflectionFalloffDistance = 0.0;
  98461. /**
  98462. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98463. */
  98464. _this.reflectionAmount = 1.0;
  98465. /**
  98466. * This specifies the weight of the reflection at grazing angle.
  98467. */
  98468. _this.reflectionReflectance0 = 0.05;
  98469. /**
  98470. * This specifies the weight of the reflection at a perpendicular point of view.
  98471. */
  98472. _this.reflectionReflectance90 = 0.5;
  98473. /**
  98474. * Helps to directly use the maps channels instead of their level.
  98475. */
  98476. _this.useRGBColor = true;
  98477. /**
  98478. * This helps reducing the banding effect that could occur on the background.
  98479. */
  98480. _this.enableNoise = false;
  98481. _this._fovMultiplier = 1.0;
  98482. /**
  98483. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98484. */
  98485. _this.useEquirectangularFOV = false;
  98486. _this._maxSimultaneousLights = 4;
  98487. /**
  98488. * Number of Simultaneous lights allowed on the material.
  98489. */
  98490. _this.maxSimultaneousLights = 4;
  98491. /**
  98492. * Keep track of the image processing observer to allow dispose and replace.
  98493. */
  98494. _this._imageProcessingObserver = null;
  98495. /**
  98496. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98497. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98498. */
  98499. _this.switchToBGR = false;
  98500. // Temp values kept as cache in the material.
  98501. _this._renderTargets = new BABYLON.SmartArray(16);
  98502. _this._reflectionControls = BABYLON.Vector4.Zero();
  98503. _this._white = BABYLON.Color3.White();
  98504. _this._primaryShadowColor = BABYLON.Color3.Black();
  98505. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98506. // Setup the default processing configuration to the scene.
  98507. _this._attachImageProcessingConfiguration(null);
  98508. _this.getRenderTargetTextures = function () {
  98509. _this._renderTargets.reset();
  98510. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98511. _this._renderTargets.push(_this._diffuseTexture);
  98512. }
  98513. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98514. _this._renderTargets.push(_this._reflectionTexture);
  98515. }
  98516. return _this._renderTargets;
  98517. };
  98518. return _this;
  98519. }
  98520. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98521. /**
  98522. * Experimental Internal Use Only.
  98523. *
  98524. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98525. * This acts as a helper to set the primary color to a more "human friendly" value.
  98526. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98527. * output color as close as possible from the chosen value.
  98528. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98529. * part of lighting setup.)
  98530. */
  98531. get: function () {
  98532. return this.__perceptualColor;
  98533. },
  98534. set: function (value) {
  98535. this.__perceptualColor = value;
  98536. this._computePrimaryColorFromPerceptualColor();
  98537. this._markAllSubMeshesAsLightsDirty();
  98538. },
  98539. enumerable: true,
  98540. configurable: true
  98541. });
  98542. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98543. /**
  98544. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98545. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98546. */
  98547. get: function () {
  98548. return this._primaryColorShadowLevel;
  98549. },
  98550. set: function (value) {
  98551. this._primaryColorShadowLevel = value;
  98552. this._computePrimaryColors();
  98553. this._markAllSubMeshesAsLightsDirty();
  98554. },
  98555. enumerable: true,
  98556. configurable: true
  98557. });
  98558. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98559. /**
  98560. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98561. * The primary color is used at the level chosen to define what the white area would look.
  98562. */
  98563. get: function () {
  98564. return this._primaryColorHighlightLevel;
  98565. },
  98566. set: function (value) {
  98567. this._primaryColorHighlightLevel = value;
  98568. this._computePrimaryColors();
  98569. this._markAllSubMeshesAsLightsDirty();
  98570. },
  98571. enumerable: true,
  98572. configurable: true
  98573. });
  98574. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98575. /**
  98576. * Sets the reflection reflectance fresnel values according to the default standard
  98577. * empirically know to work well :-)
  98578. */
  98579. set: function (value) {
  98580. var reflectionWeight = value;
  98581. if (reflectionWeight < 0.5) {
  98582. reflectionWeight = reflectionWeight * 2.0;
  98583. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98584. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98585. }
  98586. else {
  98587. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98588. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98589. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98590. }
  98591. },
  98592. enumerable: true,
  98593. configurable: true
  98594. });
  98595. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98596. /**
  98597. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98598. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98599. * Recommended to be keep at 1.0 except for special cases.
  98600. */
  98601. get: function () {
  98602. return this._fovMultiplier;
  98603. },
  98604. set: function (value) {
  98605. if (isNaN(value)) {
  98606. value = 1.0;
  98607. }
  98608. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98609. },
  98610. enumerable: true,
  98611. configurable: true
  98612. });
  98613. /**
  98614. * Attaches a new image processing configuration to the PBR Material.
  98615. * @param configuration (if null the scene configuration will be use)
  98616. */
  98617. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98618. var _this = this;
  98619. if (configuration === this._imageProcessingConfiguration) {
  98620. return;
  98621. }
  98622. // Detaches observer.
  98623. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98624. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98625. }
  98626. // Pick the scene configuration if needed.
  98627. if (!configuration) {
  98628. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98629. }
  98630. else {
  98631. this._imageProcessingConfiguration = configuration;
  98632. }
  98633. // Attaches observer.
  98634. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98635. _this._computePrimaryColorFromPerceptualColor();
  98636. _this._markAllSubMeshesAsImageProcessingDirty();
  98637. });
  98638. };
  98639. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98640. /**
  98641. * Gets the image processing configuration used either in this material.
  98642. */
  98643. get: function () {
  98644. return this._imageProcessingConfiguration;
  98645. },
  98646. /**
  98647. * Sets the Default image processing configuration used either in the this material.
  98648. *
  98649. * If sets to null, the scene one is in use.
  98650. */
  98651. set: function (value) {
  98652. this._attachImageProcessingConfiguration(value);
  98653. // Ensure the effect will be rebuilt.
  98654. this._markAllSubMeshesAsTexturesDirty();
  98655. },
  98656. enumerable: true,
  98657. configurable: true
  98658. });
  98659. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98660. /**
  98661. * Gets wether the color curves effect is enabled.
  98662. */
  98663. get: function () {
  98664. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98665. },
  98666. /**
  98667. * Sets wether the color curves effect is enabled.
  98668. */
  98669. set: function (value) {
  98670. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98671. },
  98672. enumerable: true,
  98673. configurable: true
  98674. });
  98675. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98676. /**
  98677. * Gets wether the color grading effect is enabled.
  98678. */
  98679. get: function () {
  98680. return this.imageProcessingConfiguration.colorGradingEnabled;
  98681. },
  98682. /**
  98683. * Gets wether the color grading effect is enabled.
  98684. */
  98685. set: function (value) {
  98686. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98687. },
  98688. enumerable: true,
  98689. configurable: true
  98690. });
  98691. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98692. /**
  98693. * Gets wether tonemapping is enabled or not.
  98694. */
  98695. get: function () {
  98696. return this._imageProcessingConfiguration.toneMappingEnabled;
  98697. },
  98698. /**
  98699. * Sets wether tonemapping is enabled or not
  98700. */
  98701. set: function (value) {
  98702. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98703. },
  98704. enumerable: true,
  98705. configurable: true
  98706. });
  98707. ;
  98708. ;
  98709. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98710. /**
  98711. * The camera exposure used on this material.
  98712. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98713. * This corresponds to a photographic exposure.
  98714. */
  98715. get: function () {
  98716. return this._imageProcessingConfiguration.exposure;
  98717. },
  98718. /**
  98719. * The camera exposure used on this material.
  98720. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98721. * This corresponds to a photographic exposure.
  98722. */
  98723. set: function (value) {
  98724. this._imageProcessingConfiguration.exposure = value;
  98725. },
  98726. enumerable: true,
  98727. configurable: true
  98728. });
  98729. ;
  98730. ;
  98731. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98732. /**
  98733. * Gets The camera contrast used on this material.
  98734. */
  98735. get: function () {
  98736. return this._imageProcessingConfiguration.contrast;
  98737. },
  98738. /**
  98739. * Sets The camera contrast used on this material.
  98740. */
  98741. set: function (value) {
  98742. this._imageProcessingConfiguration.contrast = value;
  98743. },
  98744. enumerable: true,
  98745. configurable: true
  98746. });
  98747. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98748. /**
  98749. * Gets the Color Grading 2D Lookup Texture.
  98750. */
  98751. get: function () {
  98752. return this._imageProcessingConfiguration.colorGradingTexture;
  98753. },
  98754. /**
  98755. * Sets the Color Grading 2D Lookup Texture.
  98756. */
  98757. set: function (value) {
  98758. this.imageProcessingConfiguration.colorGradingTexture = value;
  98759. },
  98760. enumerable: true,
  98761. configurable: true
  98762. });
  98763. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98764. /**
  98765. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98766. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98767. * 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;
  98768. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98769. */
  98770. get: function () {
  98771. return this.imageProcessingConfiguration.colorCurves;
  98772. },
  98773. /**
  98774. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98775. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98776. * 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;
  98777. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98778. */
  98779. set: function (value) {
  98780. this.imageProcessingConfiguration.colorCurves = value;
  98781. },
  98782. enumerable: true,
  98783. configurable: true
  98784. });
  98785. /**
  98786. * The entire material has been created in order to prevent overdraw.
  98787. * @returns false
  98788. */
  98789. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98790. return true;
  98791. };
  98792. /**
  98793. * The entire material has been created in order to prevent overdraw.
  98794. * @returns true if blending is enable
  98795. */
  98796. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98797. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98798. };
  98799. /**
  98800. * Checks wether the material is ready to be rendered for a given mesh.
  98801. * @param mesh The mesh to render
  98802. * @param subMesh The submesh to check against
  98803. * @param useInstances Specify wether or not the material is used with instances
  98804. * @returns true if all the dependencies are ready (Textures, Effects...)
  98805. */
  98806. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98807. var _this = this;
  98808. if (useInstances === void 0) { useInstances = false; }
  98809. if (subMesh.effect && this.isFrozen) {
  98810. if (this._wasPreviouslyReady) {
  98811. return true;
  98812. }
  98813. }
  98814. if (!subMesh._materialDefines) {
  98815. subMesh._materialDefines = new BackgroundMaterialDefines();
  98816. }
  98817. var scene = this.getScene();
  98818. var defines = subMesh._materialDefines;
  98819. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98820. if (defines._renderId === scene.getRenderId()) {
  98821. return true;
  98822. }
  98823. }
  98824. var engine = scene.getEngine();
  98825. // Lights
  98826. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98827. defines._needNormals = true;
  98828. // Textures
  98829. if (defines._areTexturesDirty) {
  98830. defines._needUVs = false;
  98831. if (scene.texturesEnabled) {
  98832. if (scene.getEngine().getCaps().textureLOD) {
  98833. defines.TEXTURELODSUPPORT = true;
  98834. }
  98835. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98836. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98837. return false;
  98838. }
  98839. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98840. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98841. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98842. defines.OPACITYFRESNEL = this._opacityFresnel;
  98843. }
  98844. else {
  98845. defines.DIFFUSE = false;
  98846. defines.DIFFUSEHASALPHA = false;
  98847. defines.GAMMADIFFUSE = false;
  98848. defines.OPACITYFRESNEL = false;
  98849. }
  98850. var reflectionTexture = this._reflectionTexture;
  98851. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98852. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98853. return false;
  98854. }
  98855. defines.REFLECTION = true;
  98856. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98857. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98858. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98859. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98860. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98861. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98862. defines.REFLECTIONBGR = this.switchToBGR;
  98863. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98864. defines.INVERTCUBICMAP = true;
  98865. }
  98866. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98867. switch (reflectionTexture.coordinatesMode) {
  98868. case BABYLON.Texture.EXPLICIT_MODE:
  98869. defines.REFLECTIONMAP_EXPLICIT = true;
  98870. break;
  98871. case BABYLON.Texture.PLANAR_MODE:
  98872. defines.REFLECTIONMAP_PLANAR = true;
  98873. break;
  98874. case BABYLON.Texture.PROJECTION_MODE:
  98875. defines.REFLECTIONMAP_PROJECTION = true;
  98876. break;
  98877. case BABYLON.Texture.SKYBOX_MODE:
  98878. defines.REFLECTIONMAP_SKYBOX = true;
  98879. break;
  98880. case BABYLON.Texture.SPHERICAL_MODE:
  98881. defines.REFLECTIONMAP_SPHERICAL = true;
  98882. break;
  98883. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98884. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98885. break;
  98886. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98887. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98888. break;
  98889. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98890. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98891. break;
  98892. case BABYLON.Texture.CUBIC_MODE:
  98893. case BABYLON.Texture.INVCUBIC_MODE:
  98894. default:
  98895. defines.REFLECTIONMAP_CUBIC = true;
  98896. break;
  98897. }
  98898. if (this.reflectionFresnel) {
  98899. defines.REFLECTIONFRESNEL = true;
  98900. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98901. this._reflectionControls.x = this.reflectionAmount;
  98902. this._reflectionControls.y = this.reflectionReflectance0;
  98903. this._reflectionControls.z = this.reflectionReflectance90;
  98904. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98905. }
  98906. else {
  98907. defines.REFLECTIONFRESNEL = false;
  98908. defines.REFLECTIONFALLOFF = false;
  98909. }
  98910. }
  98911. else {
  98912. defines.REFLECTION = false;
  98913. defines.REFLECTIONFRESNEL = false;
  98914. defines.REFLECTIONFALLOFF = false;
  98915. defines.REFLECTIONBLUR = false;
  98916. defines.REFLECTIONMAP_3D = false;
  98917. defines.REFLECTIONMAP_SPHERICAL = false;
  98918. defines.REFLECTIONMAP_PLANAR = false;
  98919. defines.REFLECTIONMAP_CUBIC = false;
  98920. defines.REFLECTIONMAP_PROJECTION = false;
  98921. defines.REFLECTIONMAP_SKYBOX = false;
  98922. defines.REFLECTIONMAP_EXPLICIT = false;
  98923. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98924. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98925. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98926. defines.INVERTCUBICMAP = false;
  98927. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98928. defines.LODINREFLECTIONALPHA = false;
  98929. defines.GAMMAREFLECTION = false;
  98930. defines.RGBDREFLECTION = false;
  98931. }
  98932. }
  98933. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98934. defines.USERGBCOLOR = this._useRGBColor;
  98935. defines.NOISE = this._enableNoise;
  98936. }
  98937. if (defines._areLightsDirty) {
  98938. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98939. }
  98940. if (defines._areImageProcessingDirty) {
  98941. if (!this._imageProcessingConfiguration.isReady()) {
  98942. return false;
  98943. }
  98944. this._imageProcessingConfiguration.prepareDefines(defines);
  98945. }
  98946. // Misc.
  98947. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98948. // Values that need to be evaluated on every frame
  98949. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98950. // Attribs
  98951. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98952. if (mesh) {
  98953. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98954. mesh.createNormals(true);
  98955. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98956. }
  98957. }
  98958. }
  98959. // Get correct effect
  98960. if (defines.isDirty) {
  98961. defines.markAsProcessed();
  98962. scene.resetCachedMaterial();
  98963. // Fallbacks
  98964. var fallbacks = new BABYLON.EffectFallbacks();
  98965. if (defines.FOG) {
  98966. fallbacks.addFallback(0, "FOG");
  98967. }
  98968. if (defines.POINTSIZE) {
  98969. fallbacks.addFallback(1, "POINTSIZE");
  98970. }
  98971. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98972. if (defines.NUM_BONE_INFLUENCERS > 0) {
  98973. fallbacks.addCPUSkinningFallback(0, mesh);
  98974. }
  98975. //Attributes
  98976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98977. if (defines.NORMAL) {
  98978. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98979. }
  98980. if (defines.UV1) {
  98981. attribs.push(BABYLON.VertexBuffer.UVKind);
  98982. }
  98983. if (defines.UV2) {
  98984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98985. }
  98986. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98987. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98988. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98989. "vFogInfos", "vFogColor", "pointSize",
  98990. "vClipPlane", "mBones",
  98991. "vPrimaryColor", "vPrimaryColorShadow",
  98992. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98993. "shadowLevel", "alpha",
  98994. "vBackgroundCenter", "vReflectionControl",
  98995. "vDiffuseInfos", "diffuseMatrix",
  98996. ];
  98997. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98998. var uniformBuffers = ["Material", "Scene"];
  98999. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99000. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99001. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99002. uniformsNames: uniforms,
  99003. uniformBuffersNames: uniformBuffers,
  99004. samplers: samplers,
  99005. defines: defines,
  99006. maxSimultaneousLights: this._maxSimultaneousLights
  99007. });
  99008. var onCompiled = function (effect) {
  99009. if (_this.onCompiled) {
  99010. _this.onCompiled(effect);
  99011. }
  99012. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99013. };
  99014. var join = defines.toString();
  99015. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99016. attributes: attribs,
  99017. uniformsNames: uniforms,
  99018. uniformBuffersNames: uniformBuffers,
  99019. samplers: samplers,
  99020. defines: join,
  99021. fallbacks: fallbacks,
  99022. onCompiled: onCompiled,
  99023. onError: this.onError,
  99024. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99025. }, engine), defines);
  99026. this.buildUniformLayout();
  99027. }
  99028. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99029. return false;
  99030. }
  99031. defines._renderId = scene.getRenderId();
  99032. this._wasPreviouslyReady = true;
  99033. return true;
  99034. };
  99035. /**
  99036. * Compute the primary color according to the chosen perceptual color.
  99037. */
  99038. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99039. if (!this.__perceptualColor) {
  99040. return;
  99041. }
  99042. this._primaryColor.copyFrom(this.__perceptualColor);
  99043. // Revert gamma space.
  99044. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99045. // Revert image processing configuration.
  99046. if (this._imageProcessingConfiguration) {
  99047. // Revert Exposure.
  99048. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99049. }
  99050. this._computePrimaryColors();
  99051. };
  99052. /**
  99053. * Compute the highlights and shadow colors according to their chosen levels.
  99054. */
  99055. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99056. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99057. return;
  99058. }
  99059. // Find the highlight color based on the configuration.
  99060. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99061. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99062. // Find the shadow color based on the configuration.
  99063. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99064. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99065. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99066. };
  99067. /**
  99068. * Build the uniform buffer used in the material.
  99069. */
  99070. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99071. // Order is important !
  99072. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99073. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99074. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99075. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99076. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99077. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99078. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99079. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99080. this._uniformBuffer.addUniform("pointSize", 1);
  99081. this._uniformBuffer.addUniform("shadowLevel", 1);
  99082. this._uniformBuffer.addUniform("alpha", 1);
  99083. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99084. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99085. this._uniformBuffer.create();
  99086. };
  99087. /**
  99088. * Unbind the material.
  99089. */
  99090. BackgroundMaterial.prototype.unbind = function () {
  99091. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99092. this._uniformBuffer.setTexture("diffuseSampler", null);
  99093. }
  99094. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99095. this._uniformBuffer.setTexture("reflectionSampler", null);
  99096. }
  99097. _super.prototype.unbind.call(this);
  99098. };
  99099. /**
  99100. * Bind only the world matrix to the material.
  99101. * @param world The world matrix to bind.
  99102. */
  99103. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99104. this._activeEffect.setMatrix("world", world);
  99105. };
  99106. /**
  99107. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99108. * @param world The world matrix to bind.
  99109. * @param subMesh The submesh to bind for.
  99110. */
  99111. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99112. var scene = this.getScene();
  99113. var defines = subMesh._materialDefines;
  99114. if (!defines) {
  99115. return;
  99116. }
  99117. var effect = subMesh.effect;
  99118. if (!effect) {
  99119. return;
  99120. }
  99121. this._activeEffect = effect;
  99122. // Matrices
  99123. this.bindOnlyWorldMatrix(world);
  99124. // Bones
  99125. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99126. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99127. if (mustRebind) {
  99128. this._uniformBuffer.bindToEffect(effect, "Material");
  99129. this.bindViewProjection(effect);
  99130. var reflectionTexture = this._reflectionTexture;
  99131. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99132. // Texture uniforms
  99133. if (scene.texturesEnabled) {
  99134. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99135. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99136. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99137. }
  99138. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99139. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99140. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99141. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99142. }
  99143. }
  99144. if (this.shadowLevel > 0) {
  99145. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99146. }
  99147. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99148. // Point size
  99149. if (this.pointsCloud) {
  99150. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99151. }
  99152. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99153. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99154. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99155. }
  99156. else {
  99157. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99158. }
  99159. }
  99160. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99161. // Textures
  99162. if (scene.texturesEnabled) {
  99163. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99164. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99165. }
  99166. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99167. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99168. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99169. }
  99170. else if (!defines.REFLECTIONBLUR) {
  99171. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99172. }
  99173. else {
  99174. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99175. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99176. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99177. }
  99178. if (defines.REFLECTIONFRESNEL) {
  99179. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99180. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99181. }
  99182. }
  99183. }
  99184. // Clip plane
  99185. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99186. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99187. }
  99188. if (mustRebind || !this.isFrozen) {
  99189. if (scene.lightsEnabled) {
  99190. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99191. }
  99192. // View
  99193. this.bindView(effect);
  99194. // Fog
  99195. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99196. // image processing
  99197. this._imageProcessingConfiguration.bind(this._activeEffect);
  99198. }
  99199. this._uniformBuffer.update();
  99200. this._afterBind(mesh);
  99201. };
  99202. /**
  99203. * Dispose the material.
  99204. * @param forceDisposeEffect Force disposal of the associated effect.
  99205. * @param forceDisposeTextures Force disposal of the associated textures.
  99206. */
  99207. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99208. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99209. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99210. if (forceDisposeTextures) {
  99211. if (this.diffuseTexture) {
  99212. this.diffuseTexture.dispose();
  99213. }
  99214. if (this.reflectionTexture) {
  99215. this.reflectionTexture.dispose();
  99216. }
  99217. }
  99218. this._renderTargets.dispose();
  99219. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99220. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99221. }
  99222. _super.prototype.dispose.call(this, forceDisposeEffect);
  99223. };
  99224. /**
  99225. * Clones the material.
  99226. * @param name The cloned name.
  99227. * @returns The cloned material.
  99228. */
  99229. BackgroundMaterial.prototype.clone = function (name) {
  99230. var _this = this;
  99231. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99232. };
  99233. /**
  99234. * Serializes the current material to its JSON representation.
  99235. * @returns The JSON representation.
  99236. */
  99237. BackgroundMaterial.prototype.serialize = function () {
  99238. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99239. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99240. return serializationObject;
  99241. };
  99242. /**
  99243. * Gets the class name of the material
  99244. * @returns "BackgroundMaterial"
  99245. */
  99246. BackgroundMaterial.prototype.getClassName = function () {
  99247. return "BackgroundMaterial";
  99248. };
  99249. /**
  99250. * Parse a JSON input to create back a background material.
  99251. * @param source The JSON data to parse
  99252. * @param scene The scene to create the parsed material in
  99253. * @param rootUrl The root url of the assets the material depends upon
  99254. * @returns the instantiated BackgroundMaterial.
  99255. */
  99256. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99257. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99258. };
  99259. /**
  99260. * Standard reflectance value at parallel view angle.
  99261. */
  99262. BackgroundMaterial.StandardReflectance0 = 0.05;
  99263. /**
  99264. * Standard reflectance value at grazing angle.
  99265. */
  99266. BackgroundMaterial.StandardReflectance90 = 0.5;
  99267. __decorate([
  99268. BABYLON.serializeAsColor3()
  99269. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99270. __decorate([
  99271. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99272. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99273. __decorate([
  99274. BABYLON.serializeAsColor3()
  99275. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99276. __decorate([
  99277. BABYLON.serialize()
  99278. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99279. __decorate([
  99280. BABYLON.serialize()
  99281. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99282. __decorate([
  99283. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99284. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99285. __decorate([
  99286. BABYLON.serializeAsTexture()
  99287. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99288. __decorate([
  99289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99290. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99291. __decorate([
  99292. BABYLON.serialize()
  99293. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99294. __decorate([
  99295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99296. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99297. __decorate([
  99298. BABYLON.serializeAsTexture()
  99299. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99300. __decorate([
  99301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99302. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99303. __decorate([
  99304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99305. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99306. __decorate([
  99307. BABYLON.serialize()
  99308. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99309. __decorate([
  99310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99311. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99312. __decorate([
  99313. BABYLON.serializeAsVector3()
  99314. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99315. __decorate([
  99316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99317. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99318. __decorate([
  99319. BABYLON.serialize()
  99320. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99321. __decorate([
  99322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99323. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99324. __decorate([
  99325. BABYLON.serialize()
  99326. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99327. __decorate([
  99328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99329. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99330. __decorate([
  99331. BABYLON.serialize()
  99332. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99333. __decorate([
  99334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99335. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99336. __decorate([
  99337. BABYLON.serialize()
  99338. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99339. __decorate([
  99340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99341. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99342. __decorate([
  99343. BABYLON.serialize()
  99344. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99345. __decorate([
  99346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99347. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99348. __decorate([
  99349. BABYLON.serialize()
  99350. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99351. __decorate([
  99352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99353. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99354. __decorate([
  99355. BABYLON.serialize()
  99356. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99357. __decorate([
  99358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99359. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99360. __decorate([
  99361. BABYLON.serialize()
  99362. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99363. __decorate([
  99364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99365. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99366. __decorate([
  99367. BABYLON.serialize()
  99368. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99369. __decorate([
  99370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99371. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99372. __decorate([
  99373. BABYLON.serializeAsImageProcessingConfiguration()
  99374. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99375. return BackgroundMaterial;
  99376. }(BABYLON.PushMaterial));
  99377. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99378. })(BABYLON || (BABYLON = {}));
  99379. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99380. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99381. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99382. s = arguments[i];
  99383. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99384. t[p] = s[p];
  99385. }
  99386. return t;
  99387. };
  99388. var BABYLON;
  99389. (function (BABYLON) {
  99390. /**
  99391. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99392. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99393. * It also helps with the default setup of your imageProcessing configuration.
  99394. */
  99395. var EnvironmentHelper = /** @class */ (function () {
  99396. /**
  99397. * constructor
  99398. * @param options
  99399. * @param scene The scene to add the material to
  99400. */
  99401. function EnvironmentHelper(options, scene) {
  99402. var _this = this;
  99403. this._errorHandler = function (message, exception) {
  99404. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99405. };
  99406. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99407. this._scene = scene;
  99408. this.onErrorObservable = new BABYLON.Observable();
  99409. this._setupBackground();
  99410. this._setupImageProcessing();
  99411. }
  99412. /**
  99413. * Creates the default options for the helper.
  99414. */
  99415. EnvironmentHelper._getDefaultOptions = function () {
  99416. return {
  99417. createGround: true,
  99418. groundSize: 15,
  99419. groundTexture: this._groundTextureCDNUrl,
  99420. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99421. groundOpacity: 0.9,
  99422. enableGroundShadow: true,
  99423. groundShadowLevel: 0.5,
  99424. enableGroundMirror: false,
  99425. groundMirrorSizeRatio: 0.3,
  99426. groundMirrorBlurKernel: 64,
  99427. groundMirrorAmount: 1,
  99428. groundMirrorFresnelWeight: 1,
  99429. groundMirrorFallOffDistance: 0,
  99430. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99431. groundYBias: 0.00001,
  99432. createSkybox: true,
  99433. skyboxSize: 20,
  99434. skyboxTexture: this._skyboxTextureCDNUrl,
  99435. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99436. backgroundYRotation: 0,
  99437. sizeAuto: true,
  99438. rootPosition: BABYLON.Vector3.Zero(),
  99439. setupImageProcessing: true,
  99440. environmentTexture: this._environmentTextureCDNUrl,
  99441. cameraExposure: 0.8,
  99442. cameraContrast: 1.2,
  99443. toneMappingEnabled: true,
  99444. };
  99445. };
  99446. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99447. /**
  99448. * Gets the root mesh created by the helper.
  99449. */
  99450. get: function () {
  99451. return this._rootMesh;
  99452. },
  99453. enumerable: true,
  99454. configurable: true
  99455. });
  99456. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99457. /**
  99458. * Gets the skybox created by the helper.
  99459. */
  99460. get: function () {
  99461. return this._skybox;
  99462. },
  99463. enumerable: true,
  99464. configurable: true
  99465. });
  99466. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99467. /**
  99468. * Gets the skybox texture created by the helper.
  99469. */
  99470. get: function () {
  99471. return this._skyboxTexture;
  99472. },
  99473. enumerable: true,
  99474. configurable: true
  99475. });
  99476. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99477. /**
  99478. * Gets the skybox material created by the helper.
  99479. */
  99480. get: function () {
  99481. return this._skyboxMaterial;
  99482. },
  99483. enumerable: true,
  99484. configurable: true
  99485. });
  99486. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99487. /**
  99488. * Gets the ground mesh created by the helper.
  99489. */
  99490. get: function () {
  99491. return this._ground;
  99492. },
  99493. enumerable: true,
  99494. configurable: true
  99495. });
  99496. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99497. /**
  99498. * Gets the ground texture created by the helper.
  99499. */
  99500. get: function () {
  99501. return this._groundTexture;
  99502. },
  99503. enumerable: true,
  99504. configurable: true
  99505. });
  99506. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99507. /**
  99508. * Gets the ground mirror created by the helper.
  99509. */
  99510. get: function () {
  99511. return this._groundMirror;
  99512. },
  99513. enumerable: true,
  99514. configurable: true
  99515. });
  99516. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99517. /**
  99518. * Gets the ground mirror render list to helps pushing the meshes
  99519. * you wish in the ground reflection.
  99520. */
  99521. get: function () {
  99522. if (this._groundMirror) {
  99523. return this._groundMirror.renderList;
  99524. }
  99525. return null;
  99526. },
  99527. enumerable: true,
  99528. configurable: true
  99529. });
  99530. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99531. /**
  99532. * Gets the ground material created by the helper.
  99533. */
  99534. get: function () {
  99535. return this._groundMaterial;
  99536. },
  99537. enumerable: true,
  99538. configurable: true
  99539. });
  99540. /**
  99541. * Updates the background according to the new options
  99542. * @param options
  99543. */
  99544. EnvironmentHelper.prototype.updateOptions = function (options) {
  99545. var newOptions = __assign({}, this._options, options);
  99546. if (this._ground && !newOptions.createGround) {
  99547. this._ground.dispose();
  99548. this._ground = null;
  99549. }
  99550. if (this._groundMaterial && !newOptions.createGround) {
  99551. this._groundMaterial.dispose();
  99552. this._groundMaterial = null;
  99553. }
  99554. if (this._groundTexture) {
  99555. if (this._options.groundTexture != newOptions.groundTexture) {
  99556. this._groundTexture.dispose();
  99557. this._groundTexture = null;
  99558. }
  99559. }
  99560. if (this._skybox && !newOptions.createSkybox) {
  99561. this._skybox.dispose();
  99562. this._skybox = null;
  99563. }
  99564. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99565. this._skyboxMaterial.dispose();
  99566. this._skyboxMaterial = null;
  99567. }
  99568. if (this._skyboxTexture) {
  99569. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99570. this._skyboxTexture.dispose();
  99571. this._skyboxTexture = null;
  99572. }
  99573. }
  99574. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99575. this._groundMirror.dispose();
  99576. this._groundMirror = null;
  99577. }
  99578. if (this._scene.environmentTexture) {
  99579. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99580. this._scene.environmentTexture.dispose();
  99581. }
  99582. }
  99583. this._options = newOptions;
  99584. this._setupBackground();
  99585. this._setupImageProcessing();
  99586. };
  99587. /**
  99588. * Sets the primary color of all the available elements.
  99589. * @param color the main color to affect to the ground and the background
  99590. */
  99591. EnvironmentHelper.prototype.setMainColor = function (color) {
  99592. if (this.groundMaterial) {
  99593. this.groundMaterial.primaryColor = color;
  99594. }
  99595. if (this.skyboxMaterial) {
  99596. this.skyboxMaterial.primaryColor = color;
  99597. }
  99598. if (this.groundMirror) {
  99599. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99600. }
  99601. };
  99602. /**
  99603. * Setup the image processing according to the specified options.
  99604. */
  99605. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99606. if (this._options.setupImageProcessing) {
  99607. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99608. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99609. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99610. this._setupEnvironmentTexture();
  99611. }
  99612. };
  99613. /**
  99614. * Setup the environment texture according to the specified options.
  99615. */
  99616. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99617. if (this._scene.environmentTexture) {
  99618. return;
  99619. }
  99620. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99621. this._scene.environmentTexture = this._options.environmentTexture;
  99622. return;
  99623. }
  99624. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99625. this._scene.environmentTexture = environmentTexture;
  99626. };
  99627. /**
  99628. * Setup the background according to the specified options.
  99629. */
  99630. EnvironmentHelper.prototype._setupBackground = function () {
  99631. if (!this._rootMesh) {
  99632. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99633. }
  99634. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99635. var sceneSize = this._getSceneSize();
  99636. if (this._options.createGround) {
  99637. this._setupGround(sceneSize);
  99638. this._setupGroundMaterial();
  99639. this._setupGroundDiffuseTexture();
  99640. if (this._options.enableGroundMirror) {
  99641. this._setupGroundMirrorTexture(sceneSize);
  99642. }
  99643. this._setupMirrorInGroundMaterial();
  99644. }
  99645. if (this._options.createSkybox) {
  99646. this._setupSkybox(sceneSize);
  99647. this._setupSkyboxMaterial();
  99648. this._setupSkyboxReflectionTexture();
  99649. }
  99650. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99651. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99652. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99653. };
  99654. /**
  99655. * Get the scene sizes according to the setup.
  99656. */
  99657. EnvironmentHelper.prototype._getSceneSize = function () {
  99658. var _this = this;
  99659. var groundSize = this._options.groundSize;
  99660. var skyboxSize = this._options.skyboxSize;
  99661. var rootPosition = this._options.rootPosition;
  99662. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99663. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99664. }
  99665. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99666. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99667. });
  99668. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99669. if (this._options.sizeAuto) {
  99670. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99671. this._scene.activeCamera.upperRadiusLimit) {
  99672. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99673. skyboxSize = groundSize;
  99674. }
  99675. var sceneDiagonalLenght = sceneDiagonal.length();
  99676. if (sceneDiagonalLenght > groundSize) {
  99677. groundSize = sceneDiagonalLenght * 2;
  99678. skyboxSize = groundSize;
  99679. }
  99680. // 10 % bigger.
  99681. groundSize *= 1.1;
  99682. skyboxSize *= 1.5;
  99683. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99684. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99685. }
  99686. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99687. };
  99688. /**
  99689. * Setup the ground according to the specified options.
  99690. */
  99691. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99692. var _this = this;
  99693. if (!this._ground) {
  99694. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99695. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99696. this._ground.parent = this._rootMesh;
  99697. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99698. }
  99699. this._ground.receiveShadows = this._options.enableGroundShadow;
  99700. };
  99701. /**
  99702. * Setup the ground material according to the specified options.
  99703. */
  99704. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99705. if (!this._groundMaterial) {
  99706. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99707. }
  99708. this._groundMaterial.alpha = this._options.groundOpacity;
  99709. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99710. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99711. this._groundMaterial.primaryColor = this._options.groundColor;
  99712. this._groundMaterial.useRGBColor = false;
  99713. this._groundMaterial.enableNoise = true;
  99714. if (this._ground) {
  99715. this._ground.material = this._groundMaterial;
  99716. }
  99717. };
  99718. /**
  99719. * Setup the ground diffuse texture according to the specified options.
  99720. */
  99721. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99722. if (!this._groundMaterial) {
  99723. return;
  99724. }
  99725. if (this._groundTexture) {
  99726. return;
  99727. }
  99728. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99729. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99730. return;
  99731. }
  99732. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99733. diffuseTexture.gammaSpace = false;
  99734. diffuseTexture.hasAlpha = true;
  99735. this._groundMaterial.diffuseTexture = diffuseTexture;
  99736. };
  99737. /**
  99738. * Setup the ground mirror texture according to the specified options.
  99739. */
  99740. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99741. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99742. if (!this._groundMirror) {
  99743. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99744. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99745. this._groundMirror.anisotropicFilteringLevel = 1;
  99746. this._groundMirror.wrapU = wrapping;
  99747. this._groundMirror.wrapV = wrapping;
  99748. this._groundMirror.gammaSpace = false;
  99749. if (this._groundMirror.renderList) {
  99750. for (var i = 0; i < this._scene.meshes.length; i++) {
  99751. var mesh = this._scene.meshes[i];
  99752. if (mesh !== this._ground &&
  99753. mesh !== this._skybox &&
  99754. mesh !== this._rootMesh) {
  99755. this._groundMirror.renderList.push(mesh);
  99756. }
  99757. }
  99758. }
  99759. }
  99760. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99761. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99762. };
  99763. /**
  99764. * Setup the ground to receive the mirror texture.
  99765. */
  99766. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99767. if (this._groundMaterial) {
  99768. this._groundMaterial.reflectionTexture = this._groundMirror;
  99769. this._groundMaterial.reflectionFresnel = true;
  99770. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99771. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99772. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99773. }
  99774. };
  99775. /**
  99776. * Setup the skybox according to the specified options.
  99777. */
  99778. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99779. var _this = this;
  99780. if (!this._skybox) {
  99781. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99782. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99783. }
  99784. this._skybox.parent = this._rootMesh;
  99785. };
  99786. /**
  99787. * Setup the skybox material according to the specified options.
  99788. */
  99789. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99790. if (!this._skybox) {
  99791. return;
  99792. }
  99793. if (!this._skyboxMaterial) {
  99794. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99795. }
  99796. this._skyboxMaterial.useRGBColor = false;
  99797. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99798. this._skyboxMaterial.enableNoise = true;
  99799. this._skybox.material = this._skyboxMaterial;
  99800. };
  99801. /**
  99802. * Setup the skybox reflection texture according to the specified options.
  99803. */
  99804. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99805. if (!this._skyboxMaterial) {
  99806. return;
  99807. }
  99808. if (this._skyboxTexture) {
  99809. return;
  99810. }
  99811. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99812. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99813. return;
  99814. }
  99815. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99816. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99817. this._skyboxTexture.gammaSpace = false;
  99818. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99819. };
  99820. /**
  99821. * Dispose all the elements created by the Helper.
  99822. */
  99823. EnvironmentHelper.prototype.dispose = function () {
  99824. if (this._groundMaterial) {
  99825. this._groundMaterial.dispose(true, true);
  99826. }
  99827. if (this._skyboxMaterial) {
  99828. this._skyboxMaterial.dispose(true, true);
  99829. }
  99830. this._rootMesh.dispose(false);
  99831. };
  99832. /**
  99833. * Default ground texture URL.
  99834. */
  99835. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99836. /**
  99837. * Default skybox texture URL.
  99838. */
  99839. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99840. /**
  99841. * Default environment texture URL.
  99842. */
  99843. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  99844. return EnvironmentHelper;
  99845. }());
  99846. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99847. })(BABYLON || (BABYLON = {}));
  99848. //# sourceMappingURL=babylon.environmentHelper.js.map
  99849. var BABYLON;
  99850. (function (BABYLON) {
  99851. /**
  99852. * This class is made for on one-liner static method to help creating particle systems.
  99853. */
  99854. var ParticleHelper = /** @class */ (function () {
  99855. function ParticleHelper() {
  99856. }
  99857. /**
  99858. * This is the main static method (one-liner) of this helper to create different particle systems.
  99859. * @param type This string represents the type to the particle system to create
  99860. * @param emitter The object where the particle system will start to emit from.
  99861. * @param scene The scene where the particle system should live.
  99862. * @param gpu If the system will use gpu.
  99863. * @returns the ParticleSystem created.
  99864. */
  99865. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99866. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99867. if (gpu === void 0) { gpu = false; }
  99868. return new Promise(function (resolve, reject) {
  99869. if (!scene) {
  99870. scene = BABYLON.Engine.LastCreatedScene;
  99871. ;
  99872. }
  99873. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99874. return reject("Particle system with GPU is not supported.");
  99875. }
  99876. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99877. var newData = JSON.parse(data.toString());
  99878. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  99879. }, undefined, undefined, undefined, function (req, exception) {
  99880. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99881. });
  99882. });
  99883. };
  99884. /**
  99885. * Static function used to create a new particle system from a IParticleSystemData
  99886. * @param data defines the source data
  99887. * @param scene defines the hosting scene
  99888. * @param emitter defines the particle emitter
  99889. * @returns a new ParticleSystem based on referenced data
  99890. */
  99891. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  99892. // Create a particle system
  99893. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  99894. // Where the particles come from
  99895. system.emitter = emitter; // the starting object, the emitter
  99896. ParticleHelper.UpdateSystem(system, data, scene);
  99897. return system;
  99898. };
  99899. /**
  99900. * Static function used to update a particle system from a IParticleSystemData
  99901. * @param system defines the particle system to update
  99902. * @param data defines the source data
  99903. * @param scene defines the hosting scene
  99904. */
  99905. ParticleHelper.UpdateSystem = function (system, data, scene) {
  99906. // Texture of each particle
  99907. if (data.textureFile) {
  99908. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  99909. }
  99910. // Colors of all particles
  99911. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99912. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99913. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99914. // Size of each particle (random between...
  99915. system.minSize = data.minSize;
  99916. system.maxSize = data.maxSize;
  99917. system.minScaleX = data.minScaleX;
  99918. system.maxScaleX = data.maxScaleX;
  99919. system.minScaleY = data.minScaleY;
  99920. system.maxScaleY = data.maxScaleY;
  99921. // Life time of each particle (random between...
  99922. system.minLifeTime = data.minLifeTime;
  99923. system.maxLifeTime = data.maxLifeTime;
  99924. // Emission rate
  99925. system.emitRate = data.emitRate;
  99926. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99927. system.blendMode = data.blendMode;
  99928. // Set the gravity of all particles
  99929. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99930. // Angular speed, in radians
  99931. system.minAngularSpeed = data.minAngularSpeed;
  99932. system.maxAngularSpeed = data.maxAngularSpeed;
  99933. // Speed
  99934. system.minEmitPower = data.minEmitPower;
  99935. system.maxEmitPower = data.maxEmitPower;
  99936. system.updateSpeed = data.updateSpeed;
  99937. switch (data.emitterType) {
  99938. case "box":
  99939. if (!data.direction1 || !data.direction2) {
  99940. throw new Error("Directions are missing in this particle system.");
  99941. }
  99942. if (!data.minEmitBox || !data.maxEmitBox) {
  99943. throw new Error("EmitBox is missing in this particle system.");
  99944. }
  99945. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  99946. break;
  99947. case "sphere":
  99948. system.createSphereEmitter(data.radius);
  99949. break;
  99950. case "directed_sphere":
  99951. if (!data.direction1 || !data.direction2) {
  99952. throw new Error("Directions are missing in this particle system.");
  99953. }
  99954. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  99955. break;
  99956. case "cone":
  99957. system.createConeEmitter(data.radius, data.angle);
  99958. break;
  99959. default:
  99960. break;
  99961. }
  99962. };
  99963. /**
  99964. * Static function used to export a particle system to a IParticleSystemData variable.
  99965. * Please note that texture file name is not exported and must be added manually
  99966. * @param system defines the particle system to export
  99967. */
  99968. ParticleHelper.ExportSystem = function (system) {
  99969. var outData = {};
  99970. // Colors of all particles
  99971. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  99972. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  99973. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  99974. // Size of each particle (random between...
  99975. outData.minSize = system.minSize;
  99976. outData.maxSize = system.maxSize;
  99977. outData.minScaleX = system.minScaleX;
  99978. outData.maxScaleX = system.maxScaleX;
  99979. outData.minScaleY = system.minScaleY;
  99980. outData.maxScaleY = system.maxScaleY;
  99981. // Life time of each particle (random between...
  99982. outData.minLifeTime = system.minLifeTime;
  99983. outData.maxLifeTime = system.maxLifeTime;
  99984. // Emission rate
  99985. outData.emitRate = system.emitRate;
  99986. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99987. outData.blendMode = system.blendMode;
  99988. // Set the gravity of all particles
  99989. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  99990. // Angular speed, in radians
  99991. outData.minAngularSpeed = system.minAngularSpeed;
  99992. outData.maxAngularSpeed = system.maxAngularSpeed;
  99993. // Speed
  99994. outData.minEmitPower = system.minEmitPower;
  99995. outData.maxEmitPower = system.maxEmitPower;
  99996. outData.updateSpeed = system.updateSpeed;
  99997. switch (system.particleEmitterType.getClassName()) {
  99998. case "BoxEmitter":
  99999. outData.emitterType = "box";
  100000. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100001. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100002. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100003. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100004. break;
  100005. case "SphereParticleEmitter":
  100006. outData.emitterType = "sphere";
  100007. outData.radius = system.particleEmitterType.radius;
  100008. break;
  100009. case "SphereDirectedParticleEmitter":
  100010. outData.emitterType = "directed_sphere";
  100011. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100012. outData.radius = sphereDirectedParticleEmitter.radius;
  100013. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100014. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100015. break;
  100016. case "ConeEmitter":
  100017. outData.emitterType = "cone";
  100018. outData.radius = system.particleEmitterType.radius;
  100019. outData.angle = system.particleEmitterType.angle;
  100020. break;
  100021. default:
  100022. break;
  100023. }
  100024. return outData;
  100025. };
  100026. /**
  100027. * Base Assets URL.
  100028. */
  100029. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100030. return ParticleHelper;
  100031. }());
  100032. BABYLON.ParticleHelper = ParticleHelper;
  100033. })(BABYLON || (BABYLON = {}));
  100034. //# sourceMappingURL=babylon.particleHelper.js.map
  100035. var BABYLON;
  100036. (function (BABYLON) {
  100037. /**
  100038. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100039. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100040. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100041. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100042. */
  100043. var VideoDome = /** @class */ (function (_super) {
  100044. __extends(VideoDome, _super);
  100045. /**
  100046. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100047. * @param name Element's name, child elements will append suffixes for their own names.
  100048. * @param urlsOrVideo defines the url(s) or the video element to use
  100049. * @param options An object containing optional or exposed sub element properties
  100050. */
  100051. function VideoDome(name, urlsOrVideo, options, scene) {
  100052. var _this = _super.call(this, name, scene) || this;
  100053. // set defaults and manage values
  100054. name = name || "videoDome";
  100055. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100056. options.clickToPlay = Boolean(options.clickToPlay);
  100057. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100058. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100059. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100060. // create
  100061. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100062. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100063. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100064. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100065. flat: false,
  100066. radius: options.size,
  100067. subdivisions: options.resolution,
  100068. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100069. }, scene);
  100070. // configure material
  100071. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100072. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100073. material.reflectionTexture = _this._videoTexture;
  100074. material.useEquirectangularFOV = true;
  100075. material.fovMultiplier = 1.0;
  100076. // configure mesh
  100077. _this._mesh.material = material;
  100078. _this._mesh.parent = _this;
  100079. // optional configuration
  100080. if (options.clickToPlay) {
  100081. scene.onPointerUp = function () {
  100082. _this._videoTexture.video.play();
  100083. };
  100084. }
  100085. return _this;
  100086. }
  100087. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100088. /**
  100089. * Gets the video texture being displayed on the sphere
  100090. */
  100091. get: function () {
  100092. return this._videoTexture;
  100093. },
  100094. enumerable: true,
  100095. configurable: true
  100096. });
  100097. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100098. /**
  100099. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100100. * Also see the options.resolution property.
  100101. */
  100102. get: function () {
  100103. return this._material.fovMultiplier;
  100104. },
  100105. set: function (value) {
  100106. this._material.fovMultiplier = value;
  100107. },
  100108. enumerable: true,
  100109. configurable: true
  100110. });
  100111. /**
  100112. * Releases resources associated with this node.
  100113. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100114. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100115. */
  100116. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100117. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100118. this._videoTexture.dispose();
  100119. this._mesh.dispose();
  100120. this._material.dispose();
  100121. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100122. };
  100123. return VideoDome;
  100124. }(BABYLON.Node));
  100125. BABYLON.VideoDome = VideoDome;
  100126. })(BABYLON || (BABYLON = {}));
  100127. //# sourceMappingURL=babylon.videoDome.js.map
  100128. var BABYLON;
  100129. (function (BABYLON) {
  100130. /**
  100131. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100132. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100133. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100134. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100135. */
  100136. var PhotoDome = /** @class */ (function (_super) {
  100137. __extends(PhotoDome, _super);
  100138. /**
  100139. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100140. * @param name Element's name, child elements will append suffixes for their own names.
  100141. * @param urlsOfPhoto define the url of the photo to display
  100142. * @param options An object containing optional or exposed sub element properties
  100143. */
  100144. function PhotoDome(name, urlOfPhoto, options, scene) {
  100145. var _this = _super.call(this, name, scene) || this;
  100146. // set defaults and manage values
  100147. name = name || "photoDome";
  100148. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100149. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100150. // create
  100151. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100152. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100153. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100154. flat: false,
  100155. radius: options.size,
  100156. subdivisions: options.resolution,
  100157. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100158. }, scene);
  100159. // configure material
  100160. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100161. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100162. material.reflectionTexture = _this._photoTexture;
  100163. material.useEquirectangularFOV = true;
  100164. material.fovMultiplier = 1.0;
  100165. // configure mesh
  100166. _this._mesh.material = material;
  100167. _this._mesh.parent = _this;
  100168. return _this;
  100169. }
  100170. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100171. /**
  100172. * Gets the texture being displayed on the sphere
  100173. */
  100174. get: function () {
  100175. return this._photoTexture;
  100176. },
  100177. enumerable: true,
  100178. configurable: true
  100179. });
  100180. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100181. /**
  100182. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100183. * Also see the options.resolution property.
  100184. */
  100185. get: function () {
  100186. return this._material.fovMultiplier;
  100187. },
  100188. set: function (value) {
  100189. this._material.fovMultiplier = value;
  100190. },
  100191. enumerable: true,
  100192. configurable: true
  100193. });
  100194. /**
  100195. * Releases resources associated with this node.
  100196. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100197. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100198. */
  100199. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100200. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100201. this._photoTexture.dispose();
  100202. this._mesh.dispose();
  100203. this._material.dispose();
  100204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100205. };
  100206. return PhotoDome;
  100207. }(BABYLON.Node));
  100208. BABYLON.PhotoDome = PhotoDome;
  100209. })(BABYLON || (BABYLON = {}));
  100210. //# sourceMappingURL=babylon.photoDome.js.map
  100211. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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(-viewDirectionW,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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 vec3 options;\nattribute vec2 size;\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; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\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); \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 vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\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 coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\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.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100212. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};